尝试使用 CMake 添加库导致错误

Trying to add libraries with CMake results in error

我正在尝试将外部 .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 to..." 错误。 Cmake编译器没有给我报错。

您在概念上是正确的,但是您没有按照 CMake 的方式进行操作。查看以下 link 关于如何 link 外部库的内容。

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