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

标签 c++ cmake clion

我正在尝试将外部 .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/

相关文章:

c++ - 为 Win IoT Core 构建 ARM 会出现 "not supported"错误

CMake 不会创建目标文件并且无法链接

svn - 使用CMake获取构建时Subversion修订版

c++ - 为 Visual Studio 2013 构建 cgicc-3.2.16

c++ - 序号 3283 找不到动态链接库 libmysql.dll

windows - CMake:如何在参数中用双引号调用 execute_process? a.k.a. 使用 CMake 中的查找来计算匹配字符串的行数

c++ - Boost.Tests 入口点在哪里?

c++ - 正确的 CMakeLists 文件

debugging - 如何使用 CLion 调试 MPI?

c++ - 为什么我的程序在读取/写入文件时丢掉最重要的数字?