Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In CMake, specify all executables target_link_libraries certain libraries

Tags:

c++

c

cmake

In CMake, is there a way to specify that all my executables links to some library? Basically I want all my executables link to tcmalloc and profiler. Simply specify -ltcmalloc and -lprofiler is not a good solution because I want to let CMake find the paths to the library in a portable way.

like image 903
Kan Li Avatar asked May 11 '12 17:05

Kan Li


People also ask

What does Target_link_libraries do in Cmake?

Specify libraries or flags to use when linking a given target and/or its dependents. Usage requirements from linked library targets will be propagated. Usage requirements of a target's dependencies affect compilation of its own sources.


2 Answers

You can override the built-in add_executable function with your own which always adds the required link dependencies:

macro (add_executable _name)
    # invoke built-in add_executable
    _add_executable(${ARGV})
    if (TARGET ${_name})
        target_link_libraries(${_name} tcmalloc profiler)
    endif()
endmacro()
like image 186
sakra Avatar answered Sep 30 '22 06:09

sakra


You can write a function/macro in CMake that does the work for you.

function(setup name sources
add_executable(name sources)
target_link_library(name tcmalloc profiler)
endfunction(setup)
setup(foo foo.c)
setup(bar bar.c)

Check out the documentation for more information.

like image 25
Stephen Newell Avatar answered Sep 30 '22 07:09

Stephen Newell