I have two different files algo1.h and algo2.h. Inside them I have anonymous namespace for tolerance.
algo1.h
namespace algo {
namespace {
double tolerance = 1e-6;
}
void algo1() {
//
}
} // namespace algo
alo2.h
namespace algo {
namespace {
double tolerance = 1e-6;
}
void algo2() {
//
}
} // namespace algo
main.cpp
#include "algo1.h"
#include "algo2.h"
int main() { algo::algo1(); }
When I try to compile I get error
error: redefinition of 'tolerance'
I thought anonymous namespace reside only inside one translation unit. That was the whole point of anonymous namespace. May be I am missing something. Can any one help to know why am I getting this error?
Also is there some good choice design where I could declare tolerance across all namespace algo.
An unnamed namespace behaves as if it had a unique namespace name for that translation unit. So the translation unit for main.cpp, after expanding out the #includes, is like:
namespace algo {
namespace unique_maincpp {
double tolerance = 1e-6;
}
void algo1() {
//
}
} // namespace algo
namespace algo {
namespace unique_maincpp {
double tolerance = 1e-6;
}
void algo2() {
}
} // namespace algo
int main() { algo::algo1(); }
and clearly you have defined algo::unique_maincpp::tolerance twice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With