将C++ main方法移动到其自己的文件时编译器错误

bhh*_*988 4 c++ program-entry-point g++

我这里有世界上最简单的节目.我想,你们中的一些人只需要一秒钟就可以找出问题所在.

foo.h中:

#ifndef FOO_H
#define FOO_H

namespace foo
{
    char str[ 20 ];

    void bar(char* s);
}

#endif
Run Code Online (Sandbox Code Playgroud)

Foo.cpp中:

#include "foo.h"

using namespace std;

namespace foo
{
    void bar(char* s) {
        return;
    }
}
Run Code Online (Sandbox Code Playgroud)

foo_main.cpp:

#include "foo.h"

using namespace std;
using namespace foo;

int main(void)
{
    bar( str );
}
Run Code Online (Sandbox Code Playgroud)

现在,当我尝试将这三个一起编译时:

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
Run Code Online (Sandbox Code Playgroud)

我想在命名空间foo中使用str作为全局,所以需要留在那里.如果我将我的main方法移动到foo.cpp,那么编译就好了.如果我想将main方法保留在单独的文件中,该怎么办?正如你所看到的,我甚至在.h文件中添加了包含警戒,这样就不会与str发生冲突,但似乎没有工作.怎么了?

Pet*_*ker 6

就像任何其他全局一样,在需要使用它的地方声明它并仅在一个地方定义它.所以foo.h,标记为extern.然后定义它foo.cpp.