简体   繁体   中英

How to link a 3rd party lib to a static library target in cmake?

I want to cmake a project like this:

Foo/
   |- libFoo/
         |- CMakeLists.txt                  
         |- foo.h
         |- foo.cpp
   |- libFooTests/
         |- CMakeLists.txt
         |- test.cpp
   |- CMakeLists.txt

# Foo/CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(Foo)
# I'm on windows, so make sure that all projects are using same runtime library
SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MTd"
SET(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MT"
ADD_SUBDIRECTORY(libFoo)
ADD_SUBDIRECTORY(libFooTests)

# Foo/libFoo/CMakeLists.txt
ADD_LIBRARY(libFoo foo.h foo.cpp)
LINK_DIRECTORIES(${THIRD_PARTY_LIB_DIR})
TARGET_LINK_LIBRARIES(libFoo lib3rdparty)

# Foo/libFooTests/CMakeLists.txt
ADD_EXECUTABLE(libFooTests test.cpp)
INCLUDE_DIRECTORIES("${PROJECT_SOURCE_DIR}/libFoo")
TARGET_LINK_LIBRARIES(libFooTests libFoo)

if I run cmake on this setup, project can be successfully generated. But it fails to build because the project generated was configured to link lib3rdparty to the test target libFooTests instead of libFoo and of course libFooTests can't know (and shouldn't know) where to find lib3rdparty .

I tried this both on windows (using generator "Visual Studio 12 2013 Win64") and on Ubuntu (using generator "Unix Makefiles").

What I expected:

${THIRD_PARTY_LIB_DIR} should be configured as library search path to libFoo target and lib3rdparty should be configured as library input for libFoo libFooTests only knows where to include headers of libFoo (aka. ${PROJECT_SOURCE_DIR}/libFoo ) and links libFoo . It shouldn't know anything about lib3rdparty

What acutally happend:

${THIRD_PARTY_LIB_DIR} seems to be ignored. lib3rdparty is a library input for libTests

What I noticed:

I noticed the Properties Page dialogs of libFoo.vcxproj and libFooTests.vcxproj in visual studio are slightly different.

The former one has a Configuration Properties | Librarian Configuration Properties | Librarian entry while the latter one has a Configuration Properties | Linker Configuration Properties | Linker instead.

How can I link lib3rdparty to libFoo only ?

You can't.

Static libraries don't get linked. A static library is just a bunch of object files packaged up into one file.

The linking happens when you link them with a complete program. So if your static library relies on another library, you have to link that library into all programs that use your static library. CMake seems to be doing the right thing here by doing this automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM