resolving redefinition of timespec in time.h

10,686

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];
Share:
10,686
Patrick Pan
Author by

Patrick Pan

Updated on June 05, 2022

Comments

  • Patrick Pan
    Patrick Pan almost 2 years

    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.

  • Patrick Pan
    Patrick Pan over 10 years
    Great trick! Neat and powerful! Thanks Jedi Yegorushkin! May the force be with you.
  • Alex Quinn
    Alex Quinn over 8 years
    How does that assert work? Is that just a way of forcing a compilation error in case the condition is false? If so, why not just use a normal assertion (i.e., via assert.h)?
  • Maxim Egorushkin
    Maxim Egorushkin over 8 years
    @AlexQuinn It is a compile time assertion, pre C++-11 static_assert. stackoverflow.com/a/14621998/412080