4

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?

2
  • Include guards help if the same header is #included twice in the same source file. It doesn't help when a header defines something and then gets included in more than one source file. Sep 2, 2012 at 21:46
  • +1 for a damn well asked question. You could have reduced even more but let’s not be picky. Sep 2, 2012 at 21:52

2 Answers 2

6

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.

3

The include directive includes the contents of the included file literally into the file containing the #include. Thus you end up with the definition char str[ 20 ]; in both cpp files, hence twice.

Write

extern char str[ 20 ];

in the header file and put

char str [ 20 ];

into only one of the cpp files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.