混合C和C ++全局变量 [英] Mixing C and C++ global variable

查看:136
本文介绍了混合C和C ++全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我们有一个类似于这样的头文件:

  typedef struct MyStruct 
{
int x;
} MyStruct;

externCMyStruct my_struct;

以前,它只包含在C ++源文件中。现在,我需要将它包含在C文件中。所以,我做以下:

  typedef struct MyStruct 
{
int x;
} MyStruct;

#ifdef __cplusplus
externCMyStruct my_struct;
#else
MyStruct my_struct;
#endif



我知道
externC
会将my_struct全局变量声明为C链接,但是这意味着如果我将这个文件包含在C编译文件以及CPP编译文件中,链接器将确定我的意图,在finally链接的可执行文件,我只想要一个用于C和CPP文件的MyStruct使用?



编辑:



采取接受答案的建议。在标题中,我有

  typedef struct MyStruct 
{
int x;
} MyStruct;

#ifdef __cplusplus
externCMyStruct my_struct;
#else
extern MyStruct my_struct;
#endif



在ppp源文件中,我有

  externC{MyStruct my_struct;} 


$因为这是头文件,你的C分支应该使用<$ c

$ c> extern 以及:

  #ifdef __cplusplus 
externCMyStruct my_struct;
#else
extern MyStruct my_struct;
#endif

否则,最终会出现 my_struct 在每个包含标题的翻译单元中,导致在链接阶段出错。



my_struct 应驻留在单独的翻译单元中 - C文件或CPP文件。还需要包含标题,以确保您获得正确的链接。


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.

解决方案

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.

这篇关于混合C和C ++全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆