Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typedef a structure to pointer with same name in C++

I'm trying to include a (.h) header file which is auto-generated by some compiler in my code. Below is the code snip from auto-generated header file.

typedef struct SequenceOfUint8 {        // Line 69
    struct SequenceOfUint8 *next;
    Uint8           value;
    } *SequenceOfUint8;                 // Line 72

If I include this header file in C code (gcc compiler), it compiles fine without any error, but if try to include this in CPP code, g++ compiler throws below mentioned error.

In file included from ssme/src/../include/xxxxx.h:39:0,
                 from ssme/src/ssme.cpp:11:
ssme/src/../include/yyyyy.h:72:4: error: conflicting declaration ‘typedef struct SequenceOfUint8* SequenceOfUint8’
 } *SequenceOfUint8;
    ^~~~~~~~~~~~~~~
ssme/src/../include/yyyyy.h:69:16: note: previous declaration as ‘struct SequenceOfUint8’
 typedef struct SequenceOfUint8 {
                ^~~~~~~~~~~~~~~

Can someone please tell how to use this in C++ code (if possible without changing the auto-generated code).

PS: I included the header file in CPP file using extern "C" { #include "yyyy.h" } statement, still no luck.

like image 824
Aditya Sharma Avatar asked Dec 29 '25 03:12

Aditya Sharma


2 Answers

You can't use it as is in C++ code. This is another instance where C and C++ being two different languages matters.

The tag namespace in C is separate, in C++ it isn't. It doesn't even exist in C++ to be precise.

Wrapping in extern "C" is also not going to make a C++ compiler treat the header as C code. That's not the intended function. The header must be standalone valid C++, which it simply isn't.

You will need to write a C wrapper, that exposes a C++ compatible API.

like image 89
StoryTeller - Unslander Monica Avatar answered Dec 31 '25 19:12

StoryTeller - Unslander Monica


Disclaimer: use this answer at your own risk. I'm not your mom.

Supposing that:

  • You can't change the generated code at all
  • There are no other use of typedef inside the generated file
  • You're not afraid of a bit of pragmatic undefined behaviour

// <Your lenghty apologetic comment here>
#define typedef static

#include <generated.h>

#undef typedef

This will replace all typedefs with static variables, which can hide types. Note that you'll need to use the elaborated type name struct SequenceOfUint8 to refer to the types later in the same file.

like image 40
Quentin Avatar answered Dec 31 '25 18:12

Quentin