Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying libraries for cmake to link to from command line

Tags:

cmake

I have a huge project managed with CMake and this project has hundreds of components each of them having own source files and each of them linking to a list of libraries, specified with target_link_libraries(${project} some_libraries, some_other_libraries)

Now, what I am aiming for is that:

Without actually modifying any of the CMakeLists.txt I want ALL the projects's target executable to link to some specific libraries.

Is there a way of achieving this? Since this is a one time trial, I don't want to manually hunt down all the CMakeLists.txt files and modify them (yes, this is the other alternative). Just a note, I compile the entire project from command line, using cmake (no cmake gui).

like image 403
Ferenc Deak Avatar asked Aug 11 '14 12:08

Ferenc Deak


People also ask

How use Cmake command line?

Running CMake from the command line From the command line, cmake can be run as an interactive question and answer session or as a non-interactive program. To run in interactive mode, just pass the option “-i” to cmake. This will cause cmake to ask you to enter a value for each value in the cache file for the project.


2 Answers

This is kind of a hack, but for a C++ project, you can use CMAKE_CXX_STANDARD_LIBRARIES. For a C project, I think you would use CMAKE_C_STANDARD_LIRBARIES.

Example for C++ that links to libbar and libfoo:

cmake ... -DCMAKE_CXX_STANDARD_LIBRARIES="-lbar -lfoo"

See the documentation here:

https://cmake.org/cmake/help/v3.6/variable/CMAKE_LANG_STANDARD_LIBRARIES.html

This won't be available for older versions of CMake; it was added some time after version 3.0.

like image 92
David Grayson Avatar answered Oct 02 '22 20:10

David Grayson


This is a dirty, dirty hack, so please only use it for testing.

You can actually overload the add_executable command by defining a function of the same name. Do this close to the top of the top-level CMakeLists.txt:

function (add_executable name)
    message("Added executable: " ${name})
    _add_executable(${name} ${ARGN})
    target_link_libraries(${name$} your_additional_lib)
endfunction()

Note that _add_executable is an internal CMake name that may break in future CMake versions. As of now (version 3.0) it seems to work with all versions though.

You can overload add_library the same way if required.

For more fine-grained control over what is linked, instead of calling target_link_libraries you can also mess with the LINK_LIBRARIES and INTERFACE_LINK_LIBRARIES target properties directly.

like image 31
ComicSansMS Avatar answered Oct 02 '22 20:10

ComicSansMS