If I declare a global variable in the header file and include it in two .cpp files, the linker gives an error saying that the character is many times defined. My question is: why does this only happen for certain types of objects (e.g. int) and not for others (e.g. enum)?
The test code used is shown below:
test.h
#ifndef TEST_HEADER
#define TEST_HEADER
namespace test
{
int i_Test1 = -1;
int i_Test2 = -1;
};
#endif
Class1.h
#ifndef CLASS_1_HEADER
#define CLASS_1_HEADER
class class1
{
public:
void count();
};
#endif
class1.cpp
#include <iostream>
#include "class1.h"
#include "test.h"
void class1::count()
{
std::cout << test::i_Test1 << std::endl;
}
class2.h
#ifndef CLASS_2_HEADER
#define CLASS_2_HEADER
class class2
{
public:
void count();
};
#endif
class2.cpp
#include "class2.h"
#include <iostream>
#include "test.h"
void class2::count()
{
std::cout << test::i_Test2 << std::endl;
}
main.cpp
#include "class1.h"
#include "class2.h"
int main(int argc, char** argv)
{
class1 c1;
class2 c2;
c1.count();
c2.count();
return -1;
}
Building this code with
g++ main.cpp class1.cpp class2.cpp -o a
outputs the following result:
ld: fatal: symbol test::i_Test1' is
multiply-defined:
(file /var/tmp//ccwWLyrM.o type=OBJT; file /var/tmp//ccOemftz.o
type=OBJT); ld: fatal: symbol
test :: i_Test2 'repeatedly defined: (file / var / tmp // ccwWLyrM.o type = OBJT; file /var/tmp//ccOemftz.o type = OBJT); ld: fatal: error file processing. There is no output written to collect2: ld returned 1 exit status
If I changed the test.h file as shown below:
test.h (with listing)
#ifndef TEST_HEADER
#define TEST_HEADER
namespace test
{
enum val
{
i_Test1 = 5,
i_Test2
};
};
#endif
" " , :
5
6