【问题标题】:How to resolve Duplicate Symbol Error?如何解决重复符号错误?
【发布时间】:2014-07-15 22:11:01
【问题描述】:

我正在一起编译 2 个 C++ 文件。 4 如果包含头文件。问题是,当链接器尝试将文件链接在一起时,我不断收到“重复符号”错误。

这是我的文件。


ma​​in.h

int test2();

ma​​in.cc

#include "main.h"
#include "test.h"

int test2(int test) {
    return 0;
}

int main() {

    test2(test());
    return 0;
}

test.h

int hello = 10;
int test();

test.cc

#include <iostream>
#include "test.h"
using namespace std;

int test() {
  cout << hello << endl;
  return 0;
}

我认为我做错了一些简单的事情。有人可以指出我做错了什么。 这是我编译文件的方式。

c++ main.cc test.cc -o main

这是我得到的错误:

duplicate symbol _hello in:
/var/folders/nj/568_95bj4dg9v11l_mksv_2m0000gn/T/main-3becdd.o
/var/folders/nj/568_95bj4dg9v11l_mksv_2m0000gn/T/test-e84473.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

【问题讨论】:

  • main.h 标头中也将 int test2(); 更改为 int test();

标签: c++ compiler-construction linker


【解决方案1】:

在头文件中,声明变量:

extern int hello;

在一个源文件中,定义变量:

int hello = 10;

不要在标题中定义变量 - 这相当于在包含标题的每个源文件中定义它们,这就是导致链接器错误的原因。

【讨论】:

    【解决方案2】:

    您可以简单地将 hello 定义为“静态”(全局)变量

    static int hello = 10;
    

    类似问题中提到了更多信息:

    Duplicate symbols while linking

    【讨论】:

      猜你喜欢
      • 2016-05-25
      • 2017-10-02
      • 2011-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-21
      • 2022-11-07
      • 2016-06-02
      相关资源
      最近更新 更多