I am having trouble understanding namespaces. A.cpp:
#include <iostream>
namespace A { int pause = 8; }
int main() {
std::cout << A::pause << std::endl;
return 0;
}
And it prints 8. However, now I add using namespace A and change A::pause to just pause. A.cpp:
#include <iostream>
namespace A { int pause = 8; }
using namespace A;
int main() {
std::cout << pause << std::endl;
return 0;
}
Now, I get the compile errors:
A.cpp: In function ‘int main()’:
A.cpp:5: error: reference to ‘pause’ is ambiguous
/usr/include/unistd.h:507: error: candidates are: int pause()
A.cpp:2: error: int A::pause
A.cpp:5: error: reference to ‘pause’ is ambiguous
/usr/include/unistd.h:507: error: candidates are: int pause()
A.cpp:2: error: int A::pause
Can someone explain what went wrong? I thought using namespace A allows me to omit the A::, similarly to how using namespace std allows you to omit std::. I tried moving the line in main()but I get the same error messages. Note, I purposefully chose the variable name pause as it apparently conflicts with the pause() declared in iostream. Any feedback is appreciated. Thanks!
The compiler is telling you what the problem is. It has two possible routes to resolve
pause– one is viaA::pauseand the other is via a functionpause()which is defined in<unistd.h>and exists outside any namespace. The compiler can’t decide which to use so you have to help it.If you chose a less generic name for your variable inside the
Anamespace, e.g.pause_val, you could output it without the namespace scoping