I can not use a global variable in main c ++

2

Class.h:

class Clase{
...
}

Class.cpp:

#include "Clase.h"
int var_global;
...

Main.cpp:

#include "Clase.h"
#include <iostream>
...
std::cout<<var_global<<std::endl;
...

The Problem

When using the variable in the main , the compiler warns me that this variable has not been declared, I tried to declare it in Class.cpp but I get that there are multiple definitions , so my question is how can I keep that variable so that it can be used both in the main and in the definition of the class.

    
asked by mistermagius 17.04.2018 в 01:07
source

1 answer

3

You almost have it.

C ++ does not compile the header files ( *.h ), copy-paste them into code files ( *.cpp ) that are compiled. Each code file creates a Translation Unit (UdT) and in each UdT there are symbols that can be your own or of other UdT, the linker will make the symbols of other UdTs available in the own UdT to generate the program final.

Each time a symbol is defined in a header file (for example, your class Clase{...} ), you are causing the symbol to be defined in the same way in all the code files in which you include said header, giving rise to several UdT with the same defined symbol and this is forbidden in C ++ by the single definition rule , that's why the compiler warns you of that there are multiple definitions.

Solution.

To start, use a inclusion guard in your Clase.h :

Clase.h
#ifndef NOMBRE_UNICO
#define NOMBRE_UNICO

class Clase{
    ...
}

#endif

Then declare var_global as external in Main.cpp

Main.cpp
#include "Clase.h"
#include <iostream>

extern int var_global;

...
std::cout<<var_global<<std::endl;
...

By the single definition rule indicated above you can not redefine var_global in Main.cpp but if the marks such as extern are telling the compiler " this symbol exists, but its definition is in another side ", when the linker finds the symbol var_global will look for the definition that is not external and will use it.

The rule for using extern is that you can have a symbol declared as extern as many times as you want but one and only one statement should not be external.

    
answered by 17.04.2018 / 08:31
source