You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Catch2 v3编译报错:undefined reference to 'ageDesc(int)' 求助

解决Catch2 v3测试中的undefined reference链接错误

你的问题核心是测试目标没有链接包含ageDesc函数实现的源文件。主程序能正常运行是因为它已经链接了src/worldmap.cpp,但当前测试目标仅将testing/test.cpp作为源文件,未包含worldmap.cpp,导致链接器找不到函数的具体实现。

修复步骤

  1. 修改CMakeLists.txt,在测试目标的源文件列表中添加src/worldmap.cpp:
add_executable(tests 
    testing/test.cpp
    src/worldmap.cpp  # 新增该行,引入业务代码实现文件
)
  1. 确认测试目标已正确包含include目录(你已完成此步骤,可跳过):
target_include_directories(tests PRIVATE include)
  1. 重新执行CMake构建流程:
cd build
cmake ..
make  # 或根据你的构建工具使用ninja等

额外优化建议

  • 务必移除test.cpp中的#define CATCH_CONFIG_MAIN,因为你已经链接了Catch2::Catch2WithMain,重复定义会引发新的编译错误。
  • 为了更便于维护,可将业务代码打包成静态库,让主程序和测试目标共同链接该库:
# 创建业务核心库
add_library(game_core STATIC src/worldmap.cpp)
target_include_directories(game_core PUBLIC include)

# 主程序链接业务库
add_executable(game main.cpp)
target_link_libraries(game PRIVATE game_core)

# 测试目标链接业务库和Catch2
add_executable(tests testing/test.cpp)
target_link_libraries(tests PRIVATE game_core Catch2::Catch2WithMain)

内容的提问来源于stack exchange,提问作者Rulz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 18:32:22