[CMake] How to link specific static libraries

Michael Hertling mhertling at online.de
Wed Jun 29 19:39:44 EDT 2011


On 06/29/2011 02:32 PM, Michael Wild wrote:
> On 06/29/2011 02:30 PM, Stephen Torri wrote:
>> Normally we use target_link_libraries to link against certain libraries.
>> For example:
>>  
>> target_link_libraries ( mytarget A B C )
>>  
>> Well when I am working on creating regressions tests for my library,
>> called mytarget, I would use the same CMake command to link against the
>> boost unit test framework library. What I curious to know is it possible
>> to set properties for a specific library, e.g. B in this scenario, to
>> say that
>> the build should always link against a static library even if the shared
>> library is present?
>>  
>> So in this case A and C would be linked as shared but B would be linked
>> as static.
>>  
>> Stephen
>>
> 
> Either use -static if you are using GCC compilers, but then you're
> linking statically against ALL libraries, or pass the full path of the
> static library to target_link_libraries().
> 
> 
> Michael

In order to ensure that the correct static library is used for linking -
even if it's located in a system directory, see [1] - you should use an
imported target and the IMPORTED_LOCATION property, e.g.:

ADD_LIBRARY(boost_unit_test_framework STATIC IMPORTED)
SET_TARGET_PROPERTIES(boost_unit_test_framework PROPERTIES
    IMPORTED_LOCATION /usr/lib/libboost_unit_test_framework.a)
TARGET_LINK_LIBRARIES(mytarget A boost_unit_test_framework C)

Otherwise, CMake might drop the path of libboost_unit_test_framework.a
and take the library from another location as the one you've intended.

Regards,

Michael

> [1] http://www.cmake.org/Wiki/CMake_2.6_Notes#Linking_to_System_Libraries


More information about the CMake mailing list