且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在多个文件中使用变量?

更新时间:2023-11-14 09:08:16

首先,请不要这样做.全局可变状态通常是一件坏事.

First off, don't do this. Global mutable state is usually a bad thing.

问题在于,链接器完成将包含声明中的文件合并后,它已经两次见过,一次在main.cpp中,一次在vars_main.cpp中:

The problem is that once the linker finishes combining the files in your include statments, it has seen this twice, once in main.cpp and once in vars_main.cpp:

int a = 1;
float b = 2.2;

如果仅将其放在头文件中,则它将以多种翻译单位显示,对于包含头文件的每个cpp文件一次.编译器不可能知道您在说a和b.

If you only put this in the header file, it shows up in multiple translation units, once for each cpp file that includes your header. It's impossible for the compiler to know which a and b you're talking about.

解决此问题的方法是在标头中声明它们extern:

The way to fix this is to declare them extern in the header:

extern int a;
extern float b;

这告诉编译器a和b是在某个地方定义的,而不一定在代码的这一部分.

This tells the compiler that a and b are defined somewhere, not necessarily in this part of the code.

然后,在您的一个cpp文件中定义它们:

Then, in one of your cpp files you would define them:

int a = 1;
float b = 2.2;

这样,在ab的生存空间中就有一个定义明确的位置,编译器可以正确地连接点.

That way, there's one well-defined place for the storage for a and b to live, and the compiler can connect the dots properly.