Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does anonymous namespace give redefinition error?

Tags:

c++

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.

like image 869
solti Avatar asked Nov 18 '25 04:11

solti


1 Answers

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.

like image 105
M.M Avatar answered Nov 19 '25 18:11

M.M