Reputation: 906
For eg., when using OpenCV, we specify
using namespace cv;
But where does C++ look down to know where it is defined?
Upvotes: 1
Views: 892
Reputation: 5665
using namespace
will not make everything declared in that namespace visible. It will expose only what translation unit "sees".
Consider following code
One.h
#pragma once
namespace ns
{
void function1();
}
Two.h
#pramga once
namespace ns
{
void function2();
}
main.cpp
#include "Two.h" // <-- included only Two.h
using namespace ns;
int main()
{
function2(); // <-- is a ns::function2() located in Two.h
function1(); // <-- error compiler does not know where to search for the function
return 0;
}
What happened here is the compiler created translation unit with all preprocessor directives resolved. It will look something like this:
namespace ns
{
void function2();
}
using namespace ns;
int main()
{
function2(); // <-- OK. Declaration is visible
function1(); // <-- Error. No declaration
return 0;
}
Upvotes: 3
Reputation: 206597
How does C++ know where to look for the namespace specified using
using namespace …
?
It doesn't.
When you use
using namespace cv;
the scope of search for names (of classes, functions, variables, enums, etc) is expanded. The names are searched in the cv
namespace in addition to other scopes in which they are normally searched.
Upvotes: 1