I have a large project that I am working on and when compiling I got a weird linker error and I can't pin the cause, I have managed to reproduce the error in a smaller example and would be really grateful if anyone can help pin the cause of the error.
basically, the project has a few files similar to:
#ifndef _TEST1_H_
#define _TEST1_H_
struct bar
{
staticint op_counter;
template<typename T>
T add(T x, T y);
template<typename T>
T minus(T x,T y);
};
int bar::op_counter(0);
template<typename T>
T bar::add(T x,T y)
{
op_counter++;
return x+y;
}
template<typename T>
T bar::minus(T x,T y)
{
op_counter++;
return x-y;
}
#endif // _TEST1_H_
test2.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#ifndef _TEST2_H_
#define _TEST2_H_
#include "test1.h" ///it seems this is causing my bug
struct foo
{
int x;
int y;
intoperator()();
};
//use code from test1.h ...
#endif // _TEST2_H_
test2.cpp <here: if i remove this file a define everything in test2.h the error disappers>
1 2 3 4 5 6
#include "test2.h"
int foo::operator()()
{return x+y;}
//some more definitions
main.h
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
#include "test2.h"
int main()
{
bar x;
foo y{34,78};
std::cout<<y()<<"\n";
std::cout<<x.add(43,89)<<"\n";
return 0;
}
even though this example does nothing it reproduces my error perfectly.
It would really help if you posted the ACTUAL error message, which would probably be enough of a clue to say what's going on.
1 2 3 4
$ g++ -std=c++11 main.cpp test2.cpp
/tmp/ccSjAMXo.o:(.bss+0x0): multiple definition of `bar::op_counter'
/tmp/ccfuTVgl.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status
Here, "multiple definition" is the key point of observation.
You get this when you put definitions inside header files, because you end up with multiple definitions (hence the error message) whenever you include such a header file.
The answer is to put the bar::op_counter thing in exactly ONE .cpp file.