I have the following header file:
class LogisticActivationFunction
{
public:
double evaluate(double x) const;
double evaluate_derivative(double x) const;
};
LogisticActivationFunction logisticActivationFunction;
Then in main.cpp I include it (and do nothing else) and I get an ld error. If I remove the declaration LogisticActivationFunction logisticActivationFunction
, I get no ld error.
The really weird part is that, if I add another header file with just:
#include "logistic_activation_function.h"
LogisticActivationFunction logisticActivationFunction;
And include that instead it compiles just fine, even though the way I though headers work it should be completely equivalent to having the declaration in the other header file.
Any ideas what causes this?
Defining a namespace scope variable in a header is a not a good idea. If the header is included into more than one translation unit (which is quite typical thing to do with a header), then there will be more than one definition, which violates the rules of the language.
In the header, you can declare a variable without defining by using the extern
linkage-specifier. Then, you can define the variable in exactly one source file. Alternatively since C++17, you can declare the variable inline
in which case no separate definition in a source file is needed.