I have the world's easiest program here. I'd imagine it'd only take a second for some of you to figure out what's wrong.
foo.h:
#ifndef FOO_H
#define FOO_H
namespace foo
{
char str[ 20 ];
void bar(char* s);
}
#endif
foo.cpp:
#include "foo.h"
using namespace std;
namespace foo
{
void bar(char* s) {
return;
}
}
foo_main.cpp:
#include "foo.h"
using namespace std;
using namespace foo;
int main(void)
{
bar( str );
}
Now when I try to compile these three together:
g++ foo_main.cpp foo.cpp -o foo
/tmp/cc22NZfj.o:(.bss+0x0): multiple definition of `foo::str'
/tmp/ccqMzzmD.o:(.bss+0x0): first defined here
collect2: ld returned 1 exit status
I want to be using str as a global within the namespace foo, so that needs to be left there. If I move my main method into foo.cpp then things compile fine. What do I do if I want to leave my main method in a separate file? As you can see, I even put include guards on the .h file so that there wouldn't be a conflict with str, but doesn't seem to be working. What's wrong?
Just like any other global, declare it wherever you need to use it and define it in one place only. So in foo.h
, mark it as extern
. Then define it in foo.cpp
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With