Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add linker flag for libraries with CMake?

Tags:

cmake

When linking a binary I can use CMAKE_EXE_LINKER_FLAGS to add a flag (let's say -Wl,-as-needed). However, if I link a library this extra flag will not be taken into account. I would need something like CMAKE_LIB_LINKER_FLAGS but I can't find it.

How should I do this?

like image 269
Barth Avatar asked Jul 02 '14 13:07

Barth


People also ask

How do I add options to CMake?

cmake -G %1 -DBUILD_SHARED_LIBS=ON -DBUILD_STATIC_LIBS=ON -DBUILD_TESTS=ON .. You have to enter all your command-line definitions before including the path. @Ébe-isaac If you want to explicitly turn an option OFF just use -DOPTION=OFF .

What does the linker flag do?

The -ObjC Linker Flag Passing the -ObjC option to the linker causes it to load all members of static libraries that implement any Objective-C class or category. This will pickup any category method implementations. But it can make the resulting executable larger, and may pickup unnecessary objects.


3 Answers

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.

like image 50
Gluttton Avatar answered Oct 16 '22 08:10

Gluttton


This is how you add linker flags to a target in modern CMake (3.13+):

# my_tgt can be an executable, library, or module.
target_link_options(my_tgt PRIVATE "LINKER:-as-needed")

Note that CMake always passes flags to the configured compiler. Thus, to forward your intended link flags to the linker, you must use the LINKER: prefix. CMake will take care of expanding it to -Wl,-as-needed on GCC, and to -Xlinker -as-needed on Clang.

See the documentation here: https://cmake.org/cmake/help/latest/command/target_link_options.html

like image 11
Alex Reinking Avatar answered Oct 16 '22 08:10

Alex Reinking


It looks like this problem is related to the one I had in CLION. I solved it by adding

{set(CMAKE_CXX_STANDARD_LIBRARIES -ljpeg)}

to CMakeLists.txt.

like image 4
JVamcas Avatar answered Oct 16 '22 06:10

JVamcas