CMake未正确链接库:Mathe::sum出现未定义引用链接错误
解决CMake链接库失败的问题
问题原因
链接错误undefined reference to Mathe::sum(int, int)的核心原因是没有正确将可执行文件与mathe库建立链接关系。你当前使用target_link_directories仅指定了库的查找目录,但未明确告诉CMake要链接哪个库文件。
解决方案
修改根目录下的CMakeLists.txt,将target_link_directories替换为target_link_libraries,直接链接mathe库目标:
修改后的根目录CMakeLists.txt
cmake_minimum_required(VERSION 3.8) project(hello LANGUAGES CXX) add_subdirectory(lib/mathe) set(SOURCE src/hello.cpp) add_executable(hello ${SOURCE}) # 替换原有的target_link_directories,直接链接mathe库目标 target_link_libraries(hello PRIVATE mathe) target_include_directories(hello PRIVATE lib/mathe)
原理说明
- 执行
add_subdirectory(lib/mathe)后,mathe库会作为CMake的一个**目标(target)**被导入到当前项目的作用域中。 target_link_libraries会让CMake自动处理库的路径、链接参数等细节,确保可执行文件能找到并链接到mathe库的实现代码。- 你在
lib/mathe/CMakeLists.txt中设置的CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS TRUE已经正确处理了Windows下动态库的符号导出问题,无需额外修改。
验证步骤
- 删除原有的构建目录(如
build) - 重新执行CMake配置和编译:
mkdir build && cd build cmake .. make
内容的提问来源于stack exchange,提问作者Kai
相关产品推荐
相关产品推荐

