gpt4 book ai didi

c++ - 如何正确初始化全局变量?

转载 作者:搜寻专家 更新时间:2023-10-31 00:15:04 24 4
gpt4 key购买 nike

<分区>

我正在写一个小学生项目,遇到了一个问题,我有几个全局变量,需要在几个源文件中使用它,但我得到了错误对变量名的 undefined reference 。例如,让我们创建三个源文件:

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"; 这样的变量应该通过不同的源文件引用。

那么,如何正确初始化全局变量呢?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com