[C++] Define a namespace and use it in multiple classes.

Hello guys.
The question I'm asking is most def a noob one. I suck at c++ and it's quite difficult to follow it's structure.
I read online about what include really means and I understand the file you're referencing just plops inside wherever you included it.

For the life of me though, can't seem to get the following scenario working:

I have a main.cpp and three files: Foo.h / Foo.cpp and Console.h.


  1. Foo does various pieces of work.
  2. Console contains a namespace (Console) and takes care of console debugging (prints stuff on an lcd).

I want to be able to call Console::Print(whatever) from any class my program might have.

However, if I include it in main.cpp, I can't use it inside Foo.cpp.

I've read about including guards, but even though I dont consider myself a slow person, I'm pretty much the Jon Snow of C++.

I'm really hoping some kind soul would provide a clear plain english explanation on how I should resolve this issue.

Thank you kindly.

You can #include "Console.h" inside of Foo.h and Foo.cpp and use the namespace as you want

Ok. So I include it in foo.cpp, as I've done. I can use it there.
What if I need to use it in main?

myFirstUsernameChoiceWasTaken:
Ok. So I include it in foo.cpp, as I've done. I can use it there.
What if I need to use it in main?

Include it in main as well.

I can't. "multiple definitions of Console.h" compiler error.
Let me show exactly what I'm trying.

//Console.h
#ifndef CONSOLE_H
#define CONSOLE_H
namespace Console
{

	void WriteLine()
	{
		//Print something
	}
}
#endif // !CONSOLE_H
//Foo.h
class Foo
{
   public:
      void DoWork();
}
//Foo.cpp
#include "Foo.h"
#include "Console.h"
void Foo::DoWork()
{

}

If I include it in main.cpp as well, I get the dreadded multiply defined symbols error. I'm most def doing it wrong.

You cannot define functions (or variables) in a header file, you can only declare them.

YES!

Finally!
That was it. Thank you.

Now it works.