Mixing C and C++ global variable

做~自己de王妃 提交于 2020-02-02 05:25:06

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/18260029/mixing-c-and-c-global-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!