I'm having a problem with defining a namespace and I know I'm going to shoot myself once I get it figured out.

Anyway, I have the following header file with namespace defined:

Code:

#ifndef __LOGGER___
#define __LOGGER___

#include <string>
#include <fstream>

using namespace std;

namespace LogFile
{
std::ofstream logFile;

void openLogFile(const char *filePath)
{
logFile.open("log.log");
}

void closeLogFile()
{
logFile.close();
}
}

#endif

Fine and dandy.

When I include the header file in more than one CPP file, I get linker errors (e.g., symbol has already been defined in ***.cpp).

Clearly I'm not doing something right. I did a search on Google but I'm not finding anything relevant (most of the results revolve around the std namespace).

I would appreciate any hints as to why I'm getting these linker errors. For an exact quote from the linker: "error LNK2005: "void __cdecl LogFile::openLogFile(const char*)" (?openLogFile@LogFile@@YAXPBD@Z) already defined in main.obj"

01-24-2009

phantomotap

Excluding templates, 'inline' functions, and macros definitions should not be in a header file.

Soma

01-24-2009

Elysia

If you include that header in two files, there will be two openLogFile functions, so the linker complains.
Namespaces aren't special in this. They merely define what you need to prefix to access the functions.
So,
either add "inline" to the functions to make sure the compiler and linker treats them as so, or,
put the declarations in the header and the definition in a source file.

01-24-2009

leeor_net

Thank you!

I've never really bothered with namespaces but they seemed an effective choice for this particular application.

Thanks again!

01-24-2009

Elysia

Oh, I love namespaces. They're always useful. Just remember that they aren't magical - the same rules that apply without them also apply with them.

01-24-2009

CornedBee

Namespace are all about names, and nothing else. They have no effect on duplication.

01-24-2009

anon

A side note, don't use the using directive in headers (since you can't "turn it off" for headers that are included after this one and might not expect std namespace to be visible) - particularly since you qualify the std::ofstream fully anyway.