【发布时间】:2014-01-12 00:55:48
【问题描述】:
我正在编写一个小学生项目,但遇到的问题是我有一些全局变量,需要在一些源文件中使用它,但是我收到错误 undefined reference to variable_name。让我们创建三个源文件,例如:
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";应该通过不同的源文件引用。 -
一般来说,静态类成员应该是首选。
标签: c++ variables global-variables