Cleaning out “using namespace std;” declarations from header files.

 | June 10, 2014 8:00 am

I recently had to work with a very large codebase, in which each and every file included a header file with the statement “using namespace
std;” in it.
This led to the situation that hundreds of header files, using std strings, pairs, etc, were using those items without any std:: dereferencing.

Cleaning this situation up by hand would have taken weeks and been error prone, so I wrote a little script to do it for me, and called it

The variable possible_offenders is a list of std c++ names which are frequently in place in the code in question.

The script recursively searches a directory for for .h and .cpp files. For cpp files, it checks if any of the possible_offenders occur in the file.  If so, it adds a “using namespace  standard” directive if none exists.  Thus cpp files are changed minimally.

For header files, all occurences of “using namespace std” are removed, and all occurences of possible_offenders are prefaced by an explicit std:: namespace specification.  Care is taken not to change occurences in comments or in quotations.

If you are faced with a similar situation, you can find the script on github:

Share on Facebook