C++ How to properly initialize global variables? [duplicate]

江枫思渺然 提交于 2021-01-27 06:45:42

问题


I'm writing little student project and stuck with the problem that I have a few global variables and need to use it in a few source files, but I get the error *undefined reference to variable_name*. Let's create three source files for example:

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();
}

When I compile and link, that's what I get:

$ 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

If I remove the extern statement, then I get the other problem, let me show:

$ 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

But I really need some variables to be global, for example my little project works with assembly code, and have a variables like string rax = "%rax %eax %ax %ah %al"; which should be referenced through different source files.

So, how to properly initialize the global variables?


回答1:


You only declared the variable but not defined it. This record

extern int global_a;

is a declaration not a definition. To define it you could in any module to write

int global_a;

Or it would be better to define function init the following way

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

and in main module before function main to write

int global_a = Init();



回答2:


tst1.cpp should read instead:

#include "tst1.h"

int global_a = 1;

void Init(){  
}

You can also write the initializer line as:

int global_a(1);

Or in C++11:

int global_a{1};

A global should only be defined (i.e. written without the extern prefix) in one source file, and not in a header file.




回答3:


you need to to add

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

to tst1.h. it included twice in tst2.cpp



来源:https://stackoverflow.com/questions/20749753/c-how-to-properly-initialize-global-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!