Search code examples
ccmakelinkertcmalloc

In CMake, specify all executables target_link_libraries certain libraries


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.


Solution

  • 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()