Linking against a library called “debug” in cmake

2019-07-14 04:44发布

问题:

We are switching to use cmake, and one of the applications I'm building use a library called "debug". (Say it's located at /path/to/libdebug.so).

I realized that following doesn't work as debug is a special keyword.

add_executable(myapp myapp.cpp)
target_link_libraries(myapp lib1 lib2 debug lib3)

Neither this works,

add_executable(myapp myapp.cpp)
target_link_libraries(myapp lib1 lib2 lib3 debug)

as it complains that

The "debug" argument must be followed by a library

Is there any workaround for this in cmake? For now to be able to continue working, I copied libdebug.so to libdebug2.so and I'm linking against debug2. But I need to find a long-term solution in cmake as libdebug.so is used by other projects too and I can't simply change it's name.

回答1:

Another approach could be creating IMPORTED target for debug library:

find_library(DEBUG_LIBRARY debug PATH <directory-contained-the-library> NO_DEFAULT_PATH)
add_library(debug_lib SHARED IMPORTED)
set_target_properties(debug_lib PROPERTIES IMPORTED_LOCATION ${DEBUG_LIBRARY})

This target then may be used for link with:

target_link_libraries(myapp lib1 lib2 lib3 debug_lib)

While this approach requires more lines (and variables) than using full library name, it is platform independent: extension of the library searched is choosen automatically by CMake.



回答2:

In cmake you can also specify a library by it's full name. This is useful when you want to specify whether you want to use the static or dynamic library.

In you case this is a workaround the reserved word "debug".

target_link_libraries(myapp lib1 lib2 lib3 libdebug.so)

A disadvantage if this approach though is you run into issues if you want to compile things in Windows too. You need then to workaround this with a variable set to either the .so or the .lib file.



标签: linker cmake