我是一位有用的助手,可以为您进行文本翻译。
我正在撰写一个小型学生项目,遇到了一些问题。我有几个全局变量需要在几个源文件中使用,但是出现了错误信息 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"; 这样的变量,应该通过不同的源文件来引用。
那么,如何正确初始化全局变量呢?
string rax =“%rax%eax%ax%ah%al”
应该通过不同的源文件进行引用。 - Hi-Angel