Force cmake to link shared library with static lib

2019-07-21 07:27发布

问题:

I am trying to make a shared library linked with a static version of librt. Currently I am doing this:

CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
ADD_LIBRARY(memtrace SHARED memtrace.c)
ADD_LIBRARY(lib_real_time STATIC IMPORTED)
SET_TARGET_PROPERTIES(lib_real_time PROPERTIES IMPORTED_LOCATION /usr/lib/x86_64-linux-gnu/librt.a)
TARGET_LINK_LIBRARIES(memtrace lib_real_time)

But I do not want to specify the path like this. Since librt is always in standard paths, I'd rather have cmake find it. Like in gcc I would only specify -lrt. When I try to do this using this cmake file:

CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
ADD_LIBRARY(memtrace SHARED memtrace.c)
TARGET_LINK_LIBRARIES(memtrace rt)

It will link memtrace with the dynamic version of librt which is not what I want!!

How can I link with the static version of librt without mentioning its full path?

回答1:

To link with the static version of the library, just add ".a" extension to it's name:

TARGET_LINK_LIBRARIES(memtrace rt.a)