尝试使用 CMake 添加库会导致错误
Trying to add libraries with CMake results in error
我正在尝试将外部.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
相关文章:
- C++ 动态数组每次添加时将大小增加 1 - 错误
- 尝试将 boost::stacktrace 添加到 CMake 项目时出现构建错误
- 这个失败的测试是将零添加到空指针未定义的行为、编译器错误还是其他什么?
- 添加符号 libgtest.so 错误:命令行中缺少 DSO
- 当 lib 已添加到其他依赖项时,如何在 VS 中调试未解析的外部符号错误
- 野牛/flex:计算器将双精度值解释为整数,所以我添加了 YYSTYPE 双精度 #define 但我有多个编译错误
- C#WPF和C++/CLI以及C++在C++/CLI中添加外部库错误
- 添加qt-libs后出现编译错误
- 试图添加两个矢量,但添加顺序错误
- 为什么自删除的全局 Vulkan 实例仅在添加层时才导致段错误?
- 添加可变参数函数的错误结果
- C++ 添加编译器警告,以错误使用自定义打印/日志功能
- 将 std::文件系统头文件添加到我的程序时出现编译错误
- 尝试向 COM 对象添加另一个接口时出现静态强制转换错误 C2440
- c++ IF 语句执行,但添加 ELSE 会显示错误
- c++ 添加具有写入文件错误的文本变量
- C 实现CNN错误添加符号:命令行中缺少DSO
- libopencv_core.so.2.4:错误添加符号:命令行中缺少DSO
- C++输出错误(添加了新问题)
- 群集不是类型 + 群集未命名类型错误.添加(群集 *)出错.不能有集群 *