我正在编写一个包含/usr/include/linux/time.h
和/usr/include/stdlib.h.
问题是:
stdlib.h
包含/usr/include/time.h
,它定义了“ struct timespec'
,而/usr/include/linux/time.h
也定义了一个。 这引入了重新定义的编译错误。
我在这两个头文件中检查了'struct timespec'
的定义:
在/usr/include/time.h中:
struct timespec { __time_t tv_sec; /* Seconds. */ long int tv_nsec; /* Nanoseconds. */ };
在/usr/include/linux/time.h中:
struct timespec { __kernel_time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ };
看来这些定义确实是等价的,但我无法certificate这一点。
我的问题是:是否有一个可靠的方法来解决这个重新定义?
关于这个问题的讨论链接也非常感谢。 谢谢。
解决双重定义错误的一种方法是重命名这些定义之一:
#include <time.h> #define timespec linux_timespec #include <linux/time.h> #undef timespec
然后在编译时断言这两个定义都具有相同的布局:
typedef int assert_same_size[sizeof(struct linux_timespec) == sizeof(timespec) ? 1 : -1]; typedef int assert_same_alignment[__alignof(struct linux_timespec) == __alignof(timespec) ? 1 : -1]; typedef int assert_same_tv_sec[offsetof(struct linux_timespec, tv_sec) == offsetof(struct timespec, tv_sec) ? 1 : -1]; typedef int assert_same_tv_nsec[offsetof(struct linux_timespec, tv_nsec) == offsetof(struct timespec, tv_nsec) ? 1 : -1];
我在Ecliepse Neon IDE中得到了同样的错误,我在C / C ++ Build – > Settings – > GCC C ++ Compiler – > Miscellaneous – > Others flag中添加了-DHAVE_STRUCT_TIMESPEC