Search code examples
c++variablesglobal-variables

How to properly initialize global variables?


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

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?


Solution

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