Patrick Pan
Patrick Pan

Reputation: 495

resolving redefinition of timespec in time.h

I am writing a program which includes both /usr/include/linux/time.h and /usr/include/stdlib.h.

The problem is:

stdlib.h includes /usr/include/time.h, which defines 'struct timespec', and /usr/include/linux/time.h also defines one. This introduces a compilation error of redefinition.

I've examined the definitions of 'struct timespec' in these two header files:

in /usr/include/time.h:

struct timespec
{
    __time_t tv_sec;            /* Seconds.  */
    long int tv_nsec;           /* Nanoseconds.  */
};

in /usr/include/linux/time.h:

struct timespec {
    __kernel_time_t tv_sec;                 /* seconds */
    long            tv_nsec;                /* nanoseconds */
}; 

It seems that these definitions are indeed equivalent, but I can't prove it.

My question is: is there a robust way to resolve this redefinition?

Links to discussions on this problem are also highly appreciated. Thanks.

Upvotes: 2

Views: 11909

Answers (2)

Akash5288
Akash5288

Reputation: 1935

I got the same error in Ecliepse Neon IDE and i resolved it by adding -DHAVE_STRUCT_TIMESPEC in C/C++ Build -> Settings -> GCC C++ Compiler -> Miscellaneous -> Others flag

enter image description here

Upvotes: 0

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136246

One way to resolve the double-definition error is to rename one of these definitions:

#include <time.h>
#define timespec linux_timespec
#include <linux/time.h>
#undef timespec

And then assert at compile time that both definitions have the same layout:

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];

Upvotes: 6

Related Questions