繁体   English   中英

CMake:检查 static C++ 库的可用性

[英]CMake: check for availability of static C++ libraries

我正在尝试静态链接多线程二进制文件。 如果 CMake 可以警告 static 库丢失,那就太好了。

注意:我知道解决方案是安装 static 库(Fedora 31 中的 libstdc++-static 和 glibc-static,如果这对任何人都有帮助的话),我只希望 CMake 报告缺少的库,而不是在构建时报告.

(作为旁注,有没有更好的方法来支持 static 链接?目前我有一些平台相关的东西可以在我们的目标系统中支持它,我还没有发现任何更便携的东西......)

这是一个示例 CMakeLists.txt:

cmake_minimum_required(VERSION 3.17)

project(test)

set(CMAKE_CXX_STANDARD 17)

add_link_options(-static)
find_package(Threads REQUIRED)

add_executable(test)
target_link_libraries(test PRIVATE Threads::Threads)

target_sources(test PRIVATE test.cpp)

这是 output:

$ cmake ..
-- The C compiler identification is GNU 9.3.1
-- The CXX compiler identification is GNU 9.3.1
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc - works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ - works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD - Failed
-- Looking for pthread_create in pthreads
-- Looking for pthread_create in pthreads - not found
-- Looking for pthread_create in pthread
-- Looking for pthread_create in pthread - found
-- Found Threads: TRUE  
-- Configuring done
-- Generating done
-- Build files have been written to: /home/sergio/src/static_cmake/build
$ make
Scanning dependencies of target test
[ 50%] Linking CXX executable test
/usr/bin/ld: cannot find -lpthread
/usr/bin/ld: cannot find -lstdc++
/usr/bin/ld: cannot find -lm
/usr/bin/ld: cannot find -lc
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/test.dir/build.make:101: test] Error 1
make[1]: *** [CMakeFiles/Makefile2:93: CMakeFiles/test.dir/all] Error 2
make: *** [Makefile:101: all] Error 2

正如所评论的,为 CMake 中的缺失库(在编译/链接之前)产生错误的一种方法是使用find_library() 如果CMake找不到具体的库,使用库变量时会报错:

# Define a variable my_pthread_static_lib to store the library, if found.
find_library(my_pthread_static_lib libpthread.a)

add_executable(test)
# Error will occur here during CMake configuration, if not found
target_link_libraries(test PRIVATE ${my_pthread_static_lib})

如果未找到my_pthread_static_lib库,则会出现此错误:

CMake Error: The following variables are used in this project, but they are set to NOTFOUND.
Please set them or make sure they are set and tested correctly in the CMake files:
my_pthread_static_lib
    linked by target "test" in directory /path/to/CMake/file

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM