10
votes

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

For example:
TARGET_LINK_LIBRARIES(ExecutableName xxx)
   where ExecutableName - is the name of executable
         xxx - is the library name.

As of my understanding CMake searches for "libxxx.so" at the paths mentioned in LINK_DIRECTORIES() macro. But if I have a third party library with name "libxxx.a" then how do I link the library to the executable using CMake.

Thank you for your help in advance!

2

2 Answers

5
votes

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.

2
votes

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.