Search code examples
cmakestatic-librariesstatic-linking

CMake to produce -L<path> -l<lib> link flags for static libraries


I'm using CMake 2.8 in order to build an application based on MQX OS (using CodeWarrior).
The CMake project basically builds a set of static libraries (let's say LIB1 and LIB2).
I then reference these libraries in the final executable cmake rule:

target_add_executable(X ${some_sources})
target_link_libraries(X LIB1 LIB2)

My problem is that some symbols are defined in more that one library.
Thus, a link command like:

mwldarm <args> -o <output> <objects> /path/to1/libLIB1.a /path/to2/libLIB2.a

would lead to multiple definition of symbols error. Instead, I would like CMake to generate a link command like:

mwldarm <args> -o <output> <objects> -L/path/to1 -L/path/to2 -lLIB -lLIB2

Question: How to get the following variables from CMAKE?

  • Libraries directories flags (ex: -L/path/to1 -L/path/to2)
  • Libraries link flags (ex: -lLIB -lLIB2)

I've read stuff concerning RPATH but it seems to concern shared libraries only. Am I right?

Thanks for advance.
I do appreciate.


Solution

  • It seems that policy CMP0003 may be what you need.

    To use it add the following line near the beginning of your CMakeLists.txt:

    CMAKE_POLICY( SET CMP0003 OLD )
    

    Another possibility is to directly set the dependencies and search path, however it's not the cleanest way. Assuming you libraries are called liba.a and libb.a, then:

    LINK_DIRECTORIES( ${paths_to_search_for} )
    TARGET_ADD_EXECUTABLE(X ${some_sources} )
    ADD_DEPENDENCIES(X LIB1 LIB2)
    TARGET_LINK_LIBRARIES(X a b )
    

    Note that in this case a and b are not cmake targets, therefore a little machinery is needed to correctly set the dependencies.