I wrote a little test snippet to clarify some things for myself.
Everywhere I looked, it says anonymous namespaces should be recognized by the compilers.
Well, mine doesn't agree.
user:~$ g++ -std=c++11 -o test Namespace_renaming_scope_demo.cpp
Namespace_renaming_scope_demo.cpp: In function ‘int main()’:
Namespace_renaming_scope_demo.cpp:28:13: error: expected identifier before ‘{’ token
namespace { int m = -1; float x = 3.14F; }
^
user:~$
Is this some super new feature or what?
Or maybe I'm supposed to use some other fancy compiler option in the command line?
I'm using g++ version 4.9.1
Look at the error message it tells you everything you need to know.
On line 28 you use the keyword "namespace", but fail to give it a token, i.e., variable name to use as you did on line 23. I admit I am not an expert when it comes to creating a name space, but this seems to be the most logical answer.
The issue is simply that you cannot create namespaces inside function bodies.
Hence you cannot create unnamed namespaces there either.
Contrary to Handy Andy's statement, the error message is misleading, because if you had given the namespace a name you would've gotten a 'namespace' definition not allowed here error which tells you the real culprit here.
What do you mean??
That's the whole point of anonymous namespaces: they are not supposed to have a name!
So there shouldn't be anything between "namespace" and "{"
At least that's what I read in all tutorials...
It's true, on cplusplus.com anonymous namespaces are not even mentioned (why would that be?) but lots of other places do mention them.
My reply above was actually for Andy, but it seems we posted more or less simultaneously, your post beating mine by some 1/4 seconds or something... :)
Thanks for this tip, this is really tricky !
No tutorial I've read mentioned this. I wasn't aware I can't declare a namespace inside a block.
I just assumed since I can rename one inside a block, declaring one would work too...