Using Namespace Laziness; Not always the Greatest Idea

Over the past few months of getting back into C++, I’ve gotten into the habit of putting using namespace clt::foo_ns; at the top of my class implementation files instead of typing out my namespace on each method. For example, instead of…

#include "Bar.h" void clt::bar_ns::Bar::do_bar_to_another_bar (const clt::bar_ns::Bar & the_bar) { //bar related logic here }

…I would just…

#include "Bar.h" using namespace clt::bar_ns; void Bar::do_bar_to_another_bar(const Bar & the_bar) { //bar related logic here }

Much easier, right? I didn’t even need to break the method signature onto a second line doing it the lazy way! Now imagine doing that on some massive class with like 50 methods. Clearly way #2 is the winner. Now, let’s see what happens when we throw a global into that namespace. Here’s one I tried not 1 hour ago:

#include "Globals.h" using namespace g6::gp_ns; void print_simulation_begin(std::string explain) { std::cout << "*" << std::endl; std::cout << "*\tSimulating:" << std::endl; std::cout << "*\t" << explain << std::endl; std::cout << "*" << std::endl; } void print_simulation_end() { std::cout << "*" << std::endl; std::cout << "*\tEnd of simulated block" << std::endl; std::cout << "*" << std::endl; }

What this is supposed to do is print a big “simulated stuff happening” banner in my homework program. What it actually does is generate a compilation error:

CardReader.cpp:25: undefined reference to `g6::gp_ns::print_simulation_begin(std::string)' CardReader.cpp:34: undefined reference to `g6::gp_ns::print_simulation_end()'

“But I defined that you stupid jerk!” I say as I slam my fist on the desk, sending the cat running. After much troubleshooting I broke down and took to the internet. I eventually stumbled on this Stack Overflow question. Apparently, if you’re writing global functions, and not class methods, you have to declare them using method #1. The following functions compile and execute as expected:

#include "Globals.h" void g6::gp_ns::print_simulation_begin (std::string explain) { std::cout << "*" << std::endl; std::cout << "*\tSimulating:" << std::endl; std::cout << "*\t" << explain << std::endl; std::cout << "*" << std::endl; } void g6::gp_ns::print_simulation_end() { std::cout << "*" << std::endl; std::cout << "*\tEnd of simulated block" << std::endl; std::cout << "*" << std::endl; }

“Don’t use using!” they said. I guess I should have listened…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: