How to link a static library to an executable using CMake

后端 未结 2 1604
梦毁少年i
梦毁少年i 2021-01-11 20:34

In CMake, we use TARGET_LINK_LIBRARIES() to link a shared library to an library/executable.

For example:
TARGET_LINK_LIBRARIES(ExecutableName xxx)
   where E         


        
相关标签:
2条回答
  • 2021-01-11 21:16

    You should always try to give either full paths or CMake targets to target_link_libraries.

    Since you do not seem to build the dependency as part of the CMake project, the only way to obtain a CMake target to link against, is to create an imported target. This is usually quite tedious to do manuall, so unless the dependency already provides a config file with an imported target, you probably do not want to go down that road. Imported targets are the most convenient to use, but only if you can get CMake to write the for you.

    So, absolute paths it is then. You obviously would not want to hardcode absolute library paths in your CMakeLists. As pointed out in your question, the desired behavior is that you specify just the name of a library and CMake should be able to figure out its location automatically. This is exactly what find_library does for you.

    To link against a library xxx, you would do something like this:

    find_library(LIB_LOCATION xxx)
    target_link_libraries(ExecutableName ${LIB_LOCATION})
    

    Note that find_library provides a plethora of options to further specify where to look for the requested library. Get rid of your existing link_directories call and add the respective paths as hints to find_library instead.

    This approach is both more flexible when porting your CMake code to other platforms and more easy to debug if something goes wrong than your initial approach.

    0 讨论(0)
  • 2021-01-11 21:30

    Just specifying the library filename should work:

    TARGET_LINK_LIBRARIES(ExecutableName libxxx.a)
    

    and

    TARGET_LINK_LIBRARIES(ExecutableName xxx)
    

    actually should work too as that would not look for the .so but for a libxxx.a file in the search paths.

    0 讨论(0)
提交回复
热议问题