首页 > 解决方案 > 通过 cmake 在 c 中链接外部 *.so 库

问题描述

我正在尝试在我的 C 项目中使用libtidy 。我构建了整洁的代码并获得了 *.so 文件。当我尝试通过 cmake 将此文件链接到我的项目时,收到以下错误消息:

CMake Error at CMakeLists.txt:8 (TARGET_LINK_LIBRARIES):
 Cannot specify link libraries for target "GLBall" which is not built by
 this project.

-- Configuring incomplete, errors occurred!
See also "/root/isefa/build/CMakeFiles/CMakeOutput.log".

这是我的CMakeLists.txt

cmake_minimum_required(VERSION 3.0.0)
project(test C CXX)
set(CMAKE_BUILD_TYPE Release)
include_directories(include)
file(GLOB SOURCES "src/*.c")
#add_library (libtidy SHARED /usr/lib)
LINK_DIRECTORIES(/usr/lib/)
TARGET_LINK_LIBRARIES(GLBall libtidy)
add_executable(test ./bin)
install (TARGETS test DESTINATION /usr/lib) 

标签: ccmaketidy

解决方案


首先,您需要在 Cmake 中找到您的库(例如,这是 Restbed 的片段):

find_library(RESTBED_LIBRARY
         NAMES 
            restbed
         PATHS 
            ${RESTBED_ROOT}/build_release
            ${RESTBED_ROOT}/Release
)

if ( NOT RESTBED_LIBRARY )
        message( WARNING "Restbed library NOT FOUND - the respective targets won't be build")
else()
        message( STATUS "Restbed library : ${RESTBED_LIBRARY}")
endif( NOT RESTBED_LIBRARY )

我在文件夹 ${RESTBED_ROOT}/build_release 中有 librestbed.so。

然后你可以链接你的目标

target_link_libraries( your_target_name ${RESTBED_LIBRARY} )

从 CMake 的角度来看,这已经足够了。


推荐阅读