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

时间:2013-12-23 19:14:14

标签: c++ variables global-variables

我正在编写一个小型学生项目,并且遇到了我有一些全局变量并需要在一些源文件中使用它的问题,但我得到错误*未定义的引用变量*。让我们创建三个源文件,例如:

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”; 应该通过不同的源文件引用。

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

3 个答案:

答案 0 :(得分:3)

您只声明了变量但未对其进行定义。这条记录

extern int global_a;

是声明而不是定义。要定义它,您可以在任何模块中编写

int global_a;

或者以下列方式定义函数init会更好

int Init { /* some code */; return 1; }

并在主模块之前写入函数main

int global_a = Init();

答案 1 :(得分:2)

tst1.cpp应该改为:

#include "tst1.h"

int global_a = 1;

void Init(){  
}

您还可以将初始化行编写为:

int global_a(1);

或者在C ++ 11中:

int global_a{1};

全局只应在一个源文件中定义(即在没有extern前缀的情况下编写),而不在中头文件。

答案 2 :(得分:0)

你需要添加

#ifndef TST1_H
#define TST1_H
.....
#endif 

到tst1.h.它在tst2.cpp中包含两次