Linking to a library that hasn't been built ye

2019-04-08 10:42发布

I'm building a project whose final output is a static library, and my CMake-based build system consists of two subdirectories - the Src and the Tests - where the build for the tests produces an executable and links the to the library which is built from src.

My problem is that the test build requires the library to already exist if it is to proceed without any errors. Is there a way to get CMake to understand that the library will exists when it comes to build the tests, or do I have to do these in separate steps?

My CMakeLists.txt files as as follows:

Root file:

cmake_minimum_required( VERSION 2.8 )
project( mylib )
add_subdirectory( Src )
add_subdirectory( Tests )

Src file:

file( GLOB MYLIB_SOURCES *.cpp )
add_library( mylib ${MYLIB_SOURCES} )

Test file:

file( GLOB MYLIB_TESTS *.cpp )
add_executable( tests ${MYLIB_TESTS} )

find_package( GTest REQUIRED )
find_library( LIB_MYLIB NAMES mylib PATHS "${CMAKE_SOURCE_DIR}/Build/Src" )

include_directories( ../Src )
include_directories( ${GTEST_INCLUDE_DIRECTORIES} )

target_link_libraries( tests ${LIB_MYLIB} ${GTEST_LIBRARIES} pthread )

标签: cmake
1条回答
贼婆χ
2楼-- · 2019-04-08 11:11

CMake should be able to figure out the dependency between Src and Tests automatically, provided of course you call CMake only on your root CMakeLists.txt. You don't really need a find_library.

So, I would keep your Src CMakeLists.txt as follows: For increased 'encapsulation' you could e.g. set 'MyLib_INCLUDE_DIRS' there and force it into the cache:

project( MyLib )
file( GLOB MYLIB_SOURCES *.cpp )
add_library( mylib ${MYLIB_SOURCES} )
# I do not know
set( mylib_INCLUDE_DIRS ${MyLib_SOURCE_DIR} CACHE STRING "Include-directories for MyLib" FORCE )

and rewrite your Tests CMakeLists.txt:

project( MyTests )
file( GLOB MYLIB_TESTS *.cpp )
add_executable( tests ${MYLIB_TESTS} )

find_package( GTest REQUIRED )
include_directories( ${mylib_INCLUDE_DIRS} )
include_directories( ${GTEST_INCLUDE_DIRECTORIES} )

target_link_libraries( tests mylib ${GTEST_LIBRARIES} pthread )

If you wish to build "tests" only, I suggest you call CMake on the root CMakeLists.txt and then step into the tests directory and call 'make' or 'msbuild'.

查看更多
登录 后发表回答