Home > Net >  conflicting declaration for typedef when using C header in C application
conflicting declaration for typedef when using C header in C application

Time:07-19

There is a header file say header1.h from a C library. In header1.h,

  51 enum ConnectionState {
  52     InProgress = 0,
  53     BannerWaitEol = 1,
  54     BannerDone = 2,
  55     Finished = 3,
  56 };
  57 typedef uint8_t ConnectionState;

I use it in my C code as

extern "C"
{
#include "header1.h"
}

But I got a compile error

header1.h:57:17: error: conflicting declaration 'typedef uint8_t ConnectionState'
 typedef uint8_t ConnectionState;
                 ^~~~~~~~~~~~~~~~~~
header1.h:51:6: note: previous declaration as 'enum ConnectionState'
 enum ConnectionState {
      ^~~~~~~~~~~~~~~~~~

I read the post: Conflicting declaration in c . And now I understand it is the typedef difference between C and C . But I can not change header1.h because it is from a third-party library. How do I use this header1.h in my C application? Thank you for your help.

CodePudding user response:

You could use push_macro/pop_macro pragmas to redefine ConnectionState to some other name and undefined the macro.

Try this:

// define ConnectionState as no-op
#define ConnectionState  ConnectionState
#pragma push_macro("ConnectionState")
#undef ConnectionState

// replace ConnectionState with ConnectionState_ and reset the macro to no-op
#define ConnectionState ConnectionState_ _Pragma("pop_macro(\"ConnectionState\")")

#include "header1.h"

It will transform:

enum ConnectionState {
    InProgress = 0,
    BannerWaitEol = 1,
    BannerDone = 2,
    Finished = 3,
};
typedef uint8_t ConnectionState;

into this:

enum ConnectionState_ {
    InProgress = 0,
    BannerWaitEol = 1,
    BannerDone = 2,
    Finished = 3,
};
typedef uint8_t ConnectionState;

It should be enough to avoid redefinition errors as long as no-one uses enum ConnectionState.

  • Related