How can I add linker flag for libraries with CMake?

Note: modern CMake has a better solution than mentioned below (see updates for details).

You can use CMAKE_SHARED_LINKER_FLAGS like:

set (CMAKE_SHARED_LINKER_FLAGS "-Wl,--as-needed")

This question looks like related.

UPD
Thanks to @Bruce Adams who points out that since v3.13 CMake has special command for such purpose: add_link_options.

UPD 2
Thanks to @Alex Reinking who points out that modern CMake doesn’t recommend using global settings. It is suggested to give the preference to the property settings before the global ones, so instead of add_link_options that has a global scope, the target_link_options should be used. See Alex’s answer for details.

Leave a Comment