Error: conflicting types for

I am working on embedded systems that provide an interface with specific types.

The problem is that some headers from the standard library I get error: conflicting types

I use gettimeofday

, and I only use struct timeval

, but it sys/time.h

also drags into time_t

, which interferes with the one defined by the system.

I cannot touch any of these pieces of code, and I need both of them.

Is there a way to get around such problems? (I should be able to use the declared types of systems and some of the functions declared in the c headers, headers that contain some of the declarations already made by the system.)

+3


source to share


3 answers


You can use macros to rename one of the time_t

typedefs without changing the headers:

#define time_t LIBC_time_t
#include <sys/time.h>
#undef time_t

#include <header_which_defines_the_time_t_you_want.h>

      



This is not guaranteed to work, but it does take a long time.

+4


source


One way to get around this, as a more or less last resort, is to introduce another layer of abstraction and provide wrapper APIs to isolate nasty headers.

If you have something like this:

my_file.c:

#include <sys/time.h>
#include <some_system_header.h>

void foo(void)
{
     struct timeval tv;
     gettimeofday(&tv);
     ....
}

      

turns into

my_gettimeofday.c:



#include <sys/time.h> //only sys.time.h here, no system headers
#include "my_gettimeofday.h"

void my_gettimeofday(struct my_timeval *my_tv)
{
   struct timeval tv;
   gettimeofday(&tv);
   my_tv->sec  = tv.tv_sec;
   my_tv->usec = tv.tv_usec;
}

      

my_gettimeofday.h:

struct my_timeval {
   long sec, usec; //adjust to your platform if needed
};
void my_gettimeofday(struct my_timeval *my_tv);

      

my_file.c:

//no sys/time.h here.
#include <some_system_header.h>
#include "my_gettimeofday.h"
void foo(void)
{
     struct my_timeval tv;
     my_gettimeofday(&tv);
     ....
}

      

+2


source


If it is only one function (gettimeofday) and one type, create a wrapper function in a separate source file, include the correct header for the gettimeofday call.

int my_gettimeofday(struct my_timeval *restrict tp, void *restrict tzp) {
    timeval t;
    t.time_t = my_timeval.time_t;
    // ...
    int ret = gettimeofday(&t, tzp);
    my_timeval.time_t = t.time_t;
    // .. copy the others
}

      

Come up with a new type, struct my_timeval, which is the same content as the one it conflicts with. The conflicts were separated.

This is true?

+1


source







All Articles