Cmake查找模块以区分共享库或静态库

Mat*_*szL 5 c++ cmake shared-libraries static-libraries

我有一个使用 libCrypto++ 的 cmake c++ 项目。我在这里托管了 FindCryptoPP.cmake 模块。重要部分是:

find_library(CryptoPP_LIBRARY
  NAMES cryptopp
  DOC "CryptoPP library"
  NO_PACKAGE_ROOT_PATH
  PATHS "/usr/lib/x86_64-linux-gnu/"
)
...
add_library(CryptoPP::CryptoPP UNKNOWN IMPORTED)
set_target_properties(CryptoPP::CryptoPP PROPERTIES
    IMPORTED_LOCATION "${CryptoPP_LIBRARY}"
    INTERFACE_INCLUDE_DIRECTORIES "${CryptoPP_INCLUDE_DIR}")
Run Code Online (Sandbox Code Playgroud)

这工作正常,找到静态库文件(*.a)。现在我想创建单独的目标 CryptoPP::CryptoPP-static 和 CryptoPP::CryptoPP-shared。安装必要的文件(默认ubuntu安装):

  • /usr/lib/x86_64-linux-gnu/libcryptopp.a
  • /usr/lib/x86_64-linux-gnu/libcryptopp.so

我想知道如何告诉 find_library 搜索静态或共享版本(最好以便携式方式 - 我需要所有 Linux、Windows、MacOS)并指定创建目标的类型。

Flo*_*ian 8

Actually CMake's default is to search first for shared libraries and then for static libraries.

The key is the order of values in the CMAKE_FIND_LIBRARY_SUFFIXES global variable, which is e.g. set in CMakeGenericSystem.cmake as part of CMake's compiler/platform detection of the project() command to:

set(CMAKE_FIND_LIBRARY_SUFFIXES ".so" ".a")
Run Code Online (Sandbox Code Playgroud)

For a solution take a look at an existing find module like FindBoost.cmake:

# Support preference of static libs by adjusting CMAKE_FIND_LIBRARY_SUFFIXES
if( Boost_USE_STATIC_LIBS )
  set( _boost_ORIG_CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES})
  if(WIN32)
    list(INSERT CMAKE_FIND_LIBRARY_SUFFIXES 0 .lib .a)
  else()
    set(CMAKE_FIND_LIBRARY_SUFFIXES .a)
  endif()
endif()
Run Code Online (Sandbox Code Playgroud)

Here the CMAKE_FIND_LIBRARY_SUFFIXES variable is temporarily changed for the find_library() calls.

Same should be applicable here. Just be aware the find_library() does cache its results if you want to do the same search twice.

References