Mixing global variable C and C ++

In my project, we have a header file similar to this:

typedef struct MyStruct { int x; } MyStruct; extern "C" MyStruct my_struct; 

Previously, it was included only in C ++ source files. Now I need to include it in the 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 global variable my_struct as C-linkage, but then it means that if I include this file in files with the Compiled file, as well as files compiled using CPP, which the linker will determine my intention, that The ultimate executable file, do I need only one MyStruct file for C and CPP?

Edit:

I accepted the advice of the accepted answer. In the title 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.

+4
source share
1 answer

Since this is a header file, your C branch should also use extern :

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

Otherwise, you will get several my_struct definitions in each translation unit, where the title will be included, which will lead to errors during the binding phase.

The definition of my_struct must be in a separate translation unit β€” either in the C file or in the CPP file. A headline should also be included to make sure you get the right link.

+9
source

Source: https://habr.com/ru/post/1497304/


All Articles