I have a namespace that I am currently using in two classes. When I try to compile my project, I get that error but my namespace is not anonymous!
One of my classes looks like this:
//margin.cpp
#include <math.h>
#include "margin.h"
#include "anotherClass.h"
#include "specificMath.nsp.h" //My namespace
double margin::doSomeMath(double a, double b){
return specificMath::math_function1(0, 1, 0);
// Just a simpler, random example
}
My namespace looks like this:
//specificMath.nsp.h
#ifndef specificMath
#define specificMath
namespace specificMath {
double math_function1(double, double, double);
double math_function1(double);
//more functions
}
//specificMath.nsp.cpp
#include <stdlib.h>
#include "constants.h"
#include "specificMath.nsp.h"
namespace specificMath{
double math_function1(double a, double b, double c){
//some code
}
... more functions
}
When I try to compile, it seems to compile fine, but when linking (and I’ve been doing “make clean” to make sure it’s using the new files) I get an error saying:
margin.o: In function `margin::doSomeMath(double, double)':
margin.cpp:(.text+0x3d): undefined reference to `(anonymous namespace)::math_function1(double, double, double)'
Why does it think it’s an anonymous namespace? How can I fix this?
I compile doing this:
g++ -I. -c -w *.h *.cpp
And then…
g++ -o myProgram *.o
You
#defined the namespace name away. After the preprocessor sees#define specificMath, then it finds all instances ofspecificMathafter that and replaces them with what you#defined it to, which in this case, is nothing. So it simply eliminates it.After the preprocessor runs
Always use all capitals for macros, and never prepend underscores to them.
for example.