ARTICLE AD BOX
Given the following three source files (main.cc, a.cc, b.cc):
// main.cc #include <iostream> #include <string> std::string get_a(); int main() { std::cout << get_a() << '\n'; return 0; } // a.cc #include <string> template <char const *p> struct Foo { std::string s{p}; }; namespace { constexpr char const name[] = "a"; } std::string get_a() { return Foo<name>().s; } // b.cc #include <string> template <char const *p> struct Foo { std::string s{p}; }; namespace { constexpr char const name[] = "b"; } std::string get_b() { return Foo<name>().s; }When compiling & linking this into an executable with gcc 14.2.1, I get the following surprising result (b instead of a is printed):
$ g++ -O0 -std=c++11 main.cc b.cc a.cc && ./a.out b
Using O1, the result is as expected:
$ g++ -O1 -std=c++11 main.cc b.cc a.cc && ./a.out a
Both gcc 13 and clang++ 20.1.8 consistently give a.
To my understanding, the anonymous namespace in both a.cc and b.cc, where name is defined, should prevent this behavior observed when using gcc 14. Is this a bug in the compiler? Or is my understanding of anonymous namespaces wrong?
