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.