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

Trying to add libraries with CMake results in error

本文关键字:错误 添加 CMake      更新时间:2023-10-16

我正在尝试将外部.lib文件添加到使用CMake的Clion项目中。我的代码非常简单,只是测试是否包含库:

#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(Project F:\Project\header\test.lib(

这应该包括库文件,但它似乎没有,因为我得到了"未定义的引用..."如上所述的错误。Cmake编译器没有给我错误。

你在概念上是正确的,但是你不是以CMake的方式这样做的。查看以下有关如何链接外部库的链接。

CMake 链接到外部库

CMAKE 不支持导入的库?

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