I have two files called file_utils.h and file_utils.cpp which contain some methods and variables which are used by different classes. Here’s an example of how it looks:
file_utils.h:
namespace my_namespace
{
extern Foo* foo;
extern Bar* bar;
void my_function(Blah* blah);
}
file_utils.cpp
#include "file_utils.h"
void my_namespace::my_function(Blah* blah)
{
foo = 0; // undefined reference to my_namespace::foo
bar = 0; // undefined reference to my_namespace::bar
//...
}
some_class.cpp
#include "file_utils.h"
some_function()
{
my_namespace::my_function(blah);
this->foo = *my_namespace::foo; // will that work ok?
}
So the errors are in the comments. If I remove the extern keyword I get multiple definition of my_namespace::foo error. What is the problem? Is that even a good idea from design standpoint or should I try to use a class with static members and methods instead?
The problem is that you only declared but not defined the variables.
You need to provide a definition in a single implementation file:
file_utils.cpp