我正在尝试将外部 .lib 文件添加到我在 Clion 中使用 CMake 的项目中。我的代码非常简单,只是为了测试库是否被包含在内:
#include <iostream>
#include "header/test.h"
int main() {
test a; // returns error saying undefined reference to 'test::test()'
return 0;
}
运行此代码时出现以下错误:
undefined reference to `test::test()'
这是因为我正在尝试制作一个测试对象,但是没有包含用于测试的库。
test.lib 文件和 test.h 文件都在我项目文件夹根目录下的“header”文件夹中。文件路径为 F:\Project\header\
我的Cmake文本文件如下:
cmake_minimum_required(VERSION 3.14)
project(Project)
set(CMAKE_CXX_STANDARD 14)
add_executable(Project main.cpp)
target_link_libraries(Project
F:\\Project\\header\\test.lib)
在 cmake 文本文件中,我使用以下行: target_link_libraries(项目F:\Project\header\test.lib)
这应该包括库文件,但它似乎没有,因为我得到了上面提到的“对...的 undefined reference ”错误。 Cmake 编译器没有给我报错。
最佳答案
您在概念上是正确的,但是您没有按照 CMake 的方式进行操作。查看以下链接,了解如何链接外部库。
CMake link to external library
cmake doesn't support imported libraries?
https://gitlab.kitware.com/cmake/community/wikis/doc/tutorials/Exporting-and-Importing-Targets
对于您的情况,如下所示):
cmake_minimum_required(VERSION 3.14)
project(Project)
set(CMAKE_CXX_STANDARD 14)
# Import the library into the CMake build system
ADD_LIBRARY(test SHARED IMPORTED)
# Specify the location of the library
SET_TARGET_PROPERTIES(TARGET test PROPERTIES IMPORTED_LOCATION “/path/to/lib/test.dll”)
# create the executable
add_executable(Project main.cpp)
# Link your exe to the library
target_link_libraries(Project test)
CMake 文档非常好。我建议您在遇到问题时检查一下。
https://cmake.org/cmake/help/latest/command/add_library.html#imported-libraries
关于c++ - 尝试使用 CMake 添加库导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57595277/