【问题标题】:Compiler error when moving C++ main method to its own file将 C++ 主方法移动到自己的文件时出现编译器错误
【发布时间】:2012-08-27 17:22:33
【问题描述】:

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

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 作为全局变量,因此需要将其保留在那里。如果我将我的 main 方法移动到 foo.cpp 中,那么一切都可以正常编译。如果我想将我的主要方法留在一个单独的文件中,我该怎么办?如您所见,我什至在 .h 文件中添加了包含保护,这样就不会与 str 发生冲突,但似乎不起作用。怎么了?

【问题讨论】:

  • 如果同一标头是#included 两次在同一源文件中,则包含保护帮助。当一个标头定义了一些东西然后被包含在多个源文件中时,它没有帮助。
  • +1 提出了一个该死的好问题。你本可以减少更多,但我们不要挑剔。

标签: c++ g++ main


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    include 指令将包含文件的内容逐字包含到包含#include 的文件中。因此,您最终会在 both cpp 文件中得到定义 char str[ 20 ];,因此是两次。

    extern char str[ 20 ];
    

    在头文件中放

    char str [ 20 ];
    

    仅存入其中一个 cpp 文件。

    【讨论】:

      猜你喜欢
      • 2014-05-18
      • 1970-01-01
      • 2015-01-25
      • 2014-02-14
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      相关资源
      最近更新 更多