Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why shouldn't I put "using namespace std" in a header? [duplicate]

Someone once hinted that doing this in a header file is not advised:

using namespace std;

Why is it not advised?

Could it cause linker errors like this: (linewrapped for convenience)

error LNK2005: "public: __thiscall std::basic_string<char,struct 
std::char_traits<char>,class std::allocator<char> >::
~basic_string<char,struct std::char_traits<char>,class std::allocator<char> > 
(void)" (??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ) 
already defined in tools.lib(Exception.obj) 
like image 799
Tony The Lion Avatar asked Mar 21 '26 19:03

Tony The Lion


2 Answers

Because it forces anyone who uses your header file to bring the std namespace into global scope. This could be a problem if they have a class that has the same name as one of the standard library classes.

like image 66
Eric Petroelje Avatar answered Mar 23 '26 08:03

Eric Petroelje


If the file gets included elsewhere the compilation unit will implicitely get the using directive. This can lead to confusing errors when names overlap.

like image 20
pmr Avatar answered Mar 23 '26 08:03

pmr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!