Cmake find module to distinguish shared or static library

♀尐吖头ヾ 提交于 2020-01-06 02:22:05

问题


I have a cmake c++ project that uses libCrypto++. I have FindCryptoPP.cmake module hosted here. Important parts are:

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}")

And this works fine, finds static library file (*.a). Now I would like to create separate targets CryptoPP::CryptoPP-static and CryptoPP::CryptoPP-shared. Necessary files are installed (default ubuntu install):

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

I want to know how to tell find_library to search either static or shared version (preferably in portable way - I need all of Linux, Windows, MacOS) and specify the type created target.


回答1:


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")

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()

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

  • Default values for CMAKE_FIND_LIBRARY_PREFIXES/CMAKE_FIND_LIBRARY_SUFFIXES
  • CMake find_library matching behavior?
  • 'find_library' returns the same value in the loop in CMake


来源:https://stackoverflow.com/questions/51121295/cmake-find-module-to-distinguish-shared-or-static-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!