Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixing C and C++ global variable

On my project, we have a header file that looks akin to this:

typedef struct MyStruct
{
  int x;
} MyStruct;

extern "C" MyStruct my_struct;

Previously, it was only included in C++ source files. Now, I have need to include it in C files. So, I do the following:

typedef struct MyStruct
{
  int x;
} MyStruct;

#ifdef __cplusplus
extern "C" MyStruct my_struct;
#else
MyStruct my_struct;
#endif

I understand that extern "C" will declare the my_struct global variable to be of C-linkage, but does this then mean that if I include this file in C-compiled files as well as CPP-compiled files that the linker will determine my intention that in the finally-linked executable, I only want one MyStruct for C and CPP files alike to use?

Edit:

I've taken the advice of the accepted answer. In the header, I have

typedef struct MyStruct
{
  int x;
} MyStruct;

#ifdef __cplusplus
extern "C" MyStruct my_struct;
#else
extern MyStruct my_struct;
#endif

And in the cpp source file, I have

extern "C" {MyStruct my_struct;}

And everything builds.

like image 537
San Jacinto Avatar asked Jan 13 '23 15:01

San Jacinto


1 Answers

Since this is the header file, your C branch should use extern as well:

#ifdef __cplusplus
extern "C" MyStruct my_struct;
#else
extern MyStruct my_struct;
#endif

Otherwise, you will end up with multiple definitions of the my_struct in every translation unit where the header is included, resulting in errors during the linking phase.

The definition of my_struct should reside in a separate translation unit - either a C file or a CPP file. The header needs to be included as well, to make sure that you get proper linkage.

like image 66
Sergey Kalinichenko Avatar answered Jan 16 '23 00:01

Sergey Kalinichenko