我正在写一个小的学生项目,并且遇到了一些问题,我有几个全局变量,需要在几个源文件中使用它,但是我得到错误* undefined引用了variable_name *。让我们创建三个源文件,例如:C++如何正确初始化全局变量?
tst1.h:
extern int global_a;
void Init();
tst1.cpp:
#include "tst1.h"
void Init(){
global_a = 1;
}
tst2.cpp:
#include "tst1.h"
int main(){
Init();
}
当我编译和链接,这就是我得到的:
$ g++ -c tst1.cpp
$ g++ -c tst2.cpp
$ g++ tst2.o tst1.o
tst1.o: In function `Init()':
tst1.cpp:(.text+0x6): undefined reference to `global_a'
collect2: error: ld returned 1 exit status
如果我删除EXTERN声明,然后我得到了另外一个问题,让我显示:
$ g++ -c tst1.cpp
$ g++ -c tst2.cpp
$ g++ tst2.o tst1.o
tst1.o:(.bss+0x0): multiple definition of `global_a'
tst2.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status
但我真的需要一些变量是全球性的,例如我的小项目与汇编代码,并有一个变量,如string rax =“%rax%eax%ax%ah%al”;应该通过不同的源文件引用它。
那么,如何正确初始化全局变量呢?
对此的最佳解决方案是不使用全局变量。有关如何避免它们的提示:依赖注入。 –
@Tim,我知道,全局变量是不好的风格,但在某些情况下,它是正确的方式。例如,如果我的项目和汇编一起工作,那么许多文件应该知道CPU寄存器的名称,并且应该通过不同的源文件引用变量'string rax ='%rax%eax%ax%ah%al';'。 –
一般来说,静态类成员应该是首选。 – leemes