Search code examples
cmakeglob

How to use cmake's target_link_libraries to link libraries matching a glob?


I have prebuilt thirdparty libraries (Boost) which I want to link to my target. All of them is stored under one directory like ${BOOST_PATH}/lib/libboost_thread.a, ${BOOST_PATH}/lib/libboost_log.a, etc. So I would like to do something like this: target_link_libraries(${TARGET} PRIVATE "${BOOST_PATH}/libboost*.a") I've read that FILE(GLOB...) might be used but strongly discouraged. And I am not sure that it would work at all. Why? How would you solve this problem if you cannot change the directory structure of the Boost libraries?


Solution

  • There are two possibilities.

    1. Using glob is discouraged because if you add a new boost library into this folder, then CMake will not automatically detect this. You will have to rerun CMake manually to pick up the new library. However, no other globbing solution would prevent this problem, except somehow doing a glob upon every build call. So what you could do is simply list all the files:

      target_link_libraries(${TARGET} PRIVATE
        "${BOOST_PATH}/libboost_filesystem.a"
        "${BOOST_PATH}/libboost_system.a"
        "${BOOST_PATH}/libboost_chrono.a"
        ...
      )
      
    2. The second solution is to use what you proposed. Something along these lines should work:

      file(GLOB LIBS "${BOOST_PATH}/libboost*.a")
      target_link_libraries(${TARGET} PRIVATE ${LIBS})