Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 移动C++;将main方法复制到它自己的文件中_C++_G++_Main - Fatal编程技术网

C++ 移动C++;将main方法复制到它自己的文件中

C++ 移动C++;将main方法复制到它自己的文件中,c++,g++,main,C++,G++,Main,我这里有世界上最简单的程序。我想你们中的一些人只需要一秒钟就能找出问题所在 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.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 );
}
现在,当我试图将这三个问题合并在一起时:

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

我想在名称空间foo中使用str作为全局变量,因此需要将其保留在那里。如果我将我的主方法移到foo.cpp中,那么事情就可以顺利进行了。如果我想将main方法保留在一个单独的文件中,该怎么办?正如您所看到的,我甚至在.h文件中添加了include-guards,这样就不会与str发生冲突,但似乎不起作用。有什么问题吗?

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

中定义它。include指令将包含文件的内容逐字包含到包含
#include
的文件中。因此,您将得到定义
charstr[20],因此有两次

在头文件中,并将

char str [ 20 ];

只有一个cpp文件。

如果同一头文件是
#在同一源文件中包含两次
d,则包含卫士帮助。当一个头文件定义了一些东西,然后被包含在多个源文件中时,它是没有帮助的。你可以减少更多,但我们不要挑剔。
char str [ 20 ];