How to set the LDFLAGS in CMakeLists.txt?

GccMakefileCmakeLdLdflags

Gcc Problem Overview


I set the CFLAGS in CMake by CMAKE_C_FLAGS. Is something like this to set LDFLAGS?

Gcc Solutions


Solution 1 - Gcc

It depends a bit on what you want:

A) If you want to specify which libraries to link to, you can use find_library to find libs and then use link_directories and target_link_libraries to.

Of course, it is often worth the effort to write a good find_package script, which nicely adds "imported" libraries with add_library( YourLib IMPORTED ) with correct locations, and platform/build specific pre- and suffixes. You can then simply refer to 'YourLib' and use target_link_libraries.

B) If you wish to specify particular linker-flags, e.g. '-mthreads' or '-Wl,--export-all-symbols' with MinGW-GCC, you can use CMAKE_EXE_LINKER_FLAGS. There are also two similar but undocumented flags for modules, shared or static libraries:

CMAKE_MODULE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS
CMAKE_STATIC_LINKER_FLAGS

Solution 2 - Gcc

Look at:

CMAKE_EXE_LINKER_FLAGS
CMAKE_MODULE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS
CMAKE_STATIC_LINKER_FLAGS

Solution 3 - Gcc

If you want to add a flag to every link, e.g. -fsanitize=address then I would not recommend using CMAKE_*_LINKER_FLAGS. Even with them all set it still doesn't use the flag when linking a framework on OSX, and maybe in other situations. Instead use link_libraries():

add_compile_options("-fsanitize=address")
link_libraries("-fsanitize=address")

This works for everything.

Solution 4 - Gcc

You can specify linker flags in target_link_libraries.

Solution 5 - Gcc

For linking against libraries see Andre's answer.

For linker flags - the following 4 CMake variables:

CMAKE_EXE_LINKER_FLAGS
CMAKE_MODULE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS
CMAKE_STATIC_LINKER_FLAGS

can be easily manipulated for different configs (debug, release...) with the ucm_add_linker_flags macro of ucm

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionhich9nView Question on Stackoverflow
Solution 1 - GccAndréView Answer on Stackoverflow
Solution 2 - GcctiburView Answer on Stackoverflow
Solution 3 - GccTimmmmView Answer on Stackoverflow
Solution 4 - GccSimonView Answer on Stackoverflow
Solution 5 - GcconqtamView Answer on Stackoverflow