How to get around not being able to use using namespace std; in C++
Question
I've encountered this issue while trying to port my C++ source code from HP-UX to Linux. When I try to compile the C++ source code on Linux, what happens is that it complains that components (from the standard C++ library) don't exist. Placing the line using namespace std; at the top of the source code seems to fix the problem. When I try to recompile the code on HP-UX, the aCC compiler complains that only namespace names are valid here ( it doesn't consider std a valid namespace ). I was wondering if there was a way to get around this issue so that the source code is binary compatible with both HP-UX's long deprecated C++ compiler and LINUX's GCC compiler.
Solution
This sucks, but you can do this:
#ifndef __HP_aCC
using namespace std;
#endif
Defines from here, and I have no way to verify.
OTHER TIPS
You could use pre-proccessors to check for the OS and whether or not to include namespace std
; So if your OS is not HP aCC, it doesn't includes std, otherwise it does. Like so:
#ifndef __HP_aCC
using namespace std;
#endif
or if you want to check for linux and win and only use namespace std if its those OS; you can also do it like this:
#if defined(WIN32) || defined(LINUX)
using namespace std;
#endif
Hope that helped!
You should be able to do this, if you really don't want #ifdef
's:
namespace std {}
using namespace std;
That is, create or extend the std
namespace. On Linux, it will extend, and on HP-UX, it will create. In either case, the using
will be valid.
However, if the HP-UX compiler is as old as you say, then the source code for including C++ header files is likely the old style:
#include <iostream.h>
Instead of the modern style:
#include <iostream>
If you have a solution around this issue, then you are probably using conditional compilation someplace in your code. If you have already localized these kind of platform specific decisions into a single place in your code, then that would be the place to add code to only do using namespace std
for those platforms that need it.
Ensure that you're including the correct headers. C++ doesn't define which standard headers might include other standard headers, so implementations behave differently when you make use of indirect includes. So just verify that everything you need to include is included directly.
Don't use
using namespace std;
just fully qualify the names you use, or useusing
declarations that call out the specific components you need.using std::string; string s; // no need for using namespace std
You can use platform-specific constants like LINUX
or WIN32
, to add or not the line using namespace std
. The usual way to do this is to make (or, more often, to generate) a config.h
file, defining aliases for platform-specific type-names that you use.