Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler error when moving C++ main method to its own file

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?

like image 265
bhh1988 Avatar asked Jan 16 '23 16:01

bhh1988


1 Answers

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.

like image 94
Pete Becker Avatar answered Feb 04 '23 16:02

Pete Becker