Gabor Marton
Gabor Marton

Reputation: 2099

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?

Upvotes: 4

Views: 25891

Answers (2)

SirDarius
SirDarius

Reputation: 42969

Or you could use CMake builtin capabilities to link with Boost, for example:

set(Boost_USE_STATIC_LIBS ON)
find_package(Boost 1.55.0 REQUIRED thread system log)

include_directories(${Boost_INCLUDE_DIRS})

target_link_libraries(${TARGET} ${Boost_LIBRARIES})

This assumes a standard installation of Boost, with the default directory layout.

I do not think globbing is a good idea because you probably do not depend on all Boost compiled libraries, and you would make linking slower for no good reason.

Even if you do, it is still a good idea to list dependencies explicitely.

Upvotes: 12

Jan Rüegg
Jan Rüegg

Reputation: 10075

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

Upvotes: 8

Related Questions