Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it wrong to use C++ 'using' keyword in a header file?

Tags:

c++

namespaces

I've been told it's bad to have "using namespace ns123" in a header file, but I can't remember what the reason given was. Is it in fact a bad thing to do, and why?

like image 863
Mr. Boy Avatar asked Feb 09 '10 21:02

Mr. Boy


People also ask

What should be in header files C?

The header file contains only declarations, and is included by the . c file for the module. Put only structure type declarations, function prototypes, and global variable extern declarations, in the . h file; put the function definitions and global variable definitions and initializations in the .

Which is the most appropriate syntax for including C header file in?

In C language, header files contain the set of predefined standard library functions. You request to use a header file in your program by including it with the C preprocessing directive “#include”. All the header file have a '. h' an extension.

Is it necessary to use header file in C?

In C program should necessarily contain the header file which stands for standard input and output used to take input with the help of scanf() and printf() function respectively.

Which keyword is used to declare a header file in C?

2. Which of the following keyword is used to declare the header file? Explanation: The include keyword is used to include all the required things to execute the given code in the program. 3.


2 Answers

It's a bad practice, in general, because it defeats the purpose of namespaces. By defining in a header you're not enforcing strict control over the scope of the using declaration, meaning that you can run into name clashes in unexpected places.

like image 92
Dan Olson Avatar answered Oct 09 '22 00:10

Dan Olson


If you put a using declaration in a header file, anything that #includes the header file also has the namespace imported, whether they want it or not. This violates the principle of least surprise and defeats the purpose of namespaces by allowing changing an #include statement to easily cause a naming collision. If you want to import a namespace in your own .cpp file to save a little typing and produce more readable code, that's fine. Just don't force users of your module to do the same.

like image 33
dsimcha Avatar answered Oct 09 '22 00:10

dsimcha