【问题标题】:Multiple definition of variable First defined here error变量的多重定义首先在这里定义错误
【发布时间】:2021-12-28 09:07:06
【问题描述】:

我有这个 c++ 项目,其中包含 .hpp 文件中的类定义和 .cpp 文件中的方法声明。 该项目使用 makefile 来构建和运行。

该程序之前运行没有错误,但 LinkedList 没有按我的意愿工作,所以我完全重写了它。 现在 LinkedList.hpp 包含类定义及其方法的声明。 我调整了其他类的方法,以便它们正确使用 LinkedList。

现在在调试程序时,我得到这个多重定义,首先在这里定义错误。

find: ‘lib’: No such file or directory
g++ -std=c++17 -Wall -Wextra -g -Iinclude -o output/main src/Game.o src/Hero.o src/Title.o src/Level.o src/Menu.o src/Entity.o src/Window.o src/main.o src/Map.o src/Object.o -lncurses 
/usr/bin/ld: src/Hero.o:/home/user/projects/project-X-githubClone/projectX/include/Object.hpp:2: multiple definition of `TileTypeStr'; src/Game.o:/home/user/projects/project-X-githubClone/projectX/include/Object.hpp:2: first defined here
/usr/bin/ld: src/Level.o:/home/user/projects/project-X-githubClone/projectX/include/Object.hpp:2: multiple definition of `TileTypeStr'; src/Game.o:/home/user/projects/project-X-githubClone/projectX/include/Object.hpp:2: first defined here
/usr/bin/ld: src/Entity.o:/home/user/projects/project-X-githubClone/projectX/include/Object.hpp:2: multiple definition of `TileTypeStr'; src/Game.o:/home/user/projects/project-X-githubClone/projectX/include/Object.hpp:2: first defined here
/usr/bin/ld: src/Map.o:/home/user/projects/project-X-githubClone/projectX/include/Object.hpp:2: multiple definition of `TileTypeStr'; src/Game.o:/home/user/projects/project-X-githubClone/projectX/include/Object.hpp:2: first defined here
collect2: error: ld returned 1 exit status
make: *** [Makefile:74: main] Error 1

所以如果我理解正确,问题是 const char* TileTypeStr[] 的多重定义。 但是为什么当我将该数组的名称更改为 tts 时,错误消息仍然显示“TileTypeStr 的多个定义”? 为什么如果我在整个项目中注释掉这个数组的唯一2个引用(包括它的声明和初始化),错误消息仍然是一样的?

【问题讨论】:

  • 如果您使用的是 c++17 - 在 const char* TileTypeStr[] 之前添加 inline 关键字
  • 错误没有改变,因为给定的命令行没有编译任何东西,它将以前编译的目标文件链接在一起。
  • 好的,谢谢@SegFault,我将 TileTypeStr[] 的定义从 .hpp 文件移动到唯一使用它的方法(在关联的 .cpp 文件中)以限制其范围,运行 make clean 和然后制作,现在一切正常。

标签: c++ compile-time multiple-definition-error


【解决方案1】:

TileTypeStr[] 毕竟放错地方了,将它移到我需要它的 toString() 方法中,然后运行 ​​ma​​ke clean 重新编译所有源文件并ma​​ke 构建 main.cpp。 通过运行 make 而不是重新编译源文件,我被困在运行错误版本的程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    相关资源
    最近更新 更多