简体   繁体   中英

CMake add_subdirectory not invoking the child CMakeLists.txt

I have a project structure like this which I wish to build using CMake.

root\
|
|--crystal\
|        |
|        |--include\ Math.h, Window.h
|        |--src\ Math.cpp, Window.cpp
|        |--lib\
|        |--CMakeLists.txt // the CHILD cmake
|
|--game\ main.cpp
|--CMakeLists.txt // the PARENT cmake

The crystal sub-project is supposed to produce a static library ( libcrystal.a ) in the lib/ folder (using the contents of include/ and src/ ) and the root project will produce an executable out of game/main.cpp linking the libcrystal.a static library.

The Parent CMAKE is as follows:

cmake_minimum_required(VERSION 2.8.1)
project(thegame)

set(CRYSTAL_LIB_DIR lib)
set(CRYSTAL_LIB_NAME crystal)

add_subdirectory(${CRYSTAL_LIB_NAME})

set(LINK_DIR ${CRYSTAL_LIB_NAME}/${CRYSTAL_LIB_DIR})

set(SRCS game/main.cpp)
link_directories(${LINK_DIR})
include_directories(${CRYSTAL_LIB_NAME}/include)

add_executable(thegame ${SRCS})
target_link_libraries(thegame lib${CRYSTAL_LIB_NAME}.a)

The child CMAKE is as follows:

cmake_minimum_required(VERSION 2.8.1)

project(crystal)

include_directories( include )
file(GLOB_RECURSE SRC "src/*.cpp")

set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CRYSTAL_LIB_DIR})
add_library(${CRYSTAL_LIB_NAME} STATIC ${SRC})

What isn't working:

When I executed cmake . and sudo make in the root/ directory I expected both parent and child cmake to run sequentially. But it seems like the child cmake is not getting invoked and thus not producing the .a file. Its showing some error like:

Scanning dependencies of target thegame
[ 20%] Building CXX object CMakeFiles/thegame.dir/game/main.cpp.o
[ 40%] Linking CXX executable thegame
/usr/bin/ld: cannot find -lcrystal
collect2: error: ld returned 1 exit status
CMakeFiles/thegame.dir/build.make:94: recipe for target 'thegame' failed
make[2]: *** [thegame] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/thegame.dir/all' failed
make[1]: *** [CMakeFiles/thegame.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

What is working:

I went ahead the did this

  1. executed cmake . in root/
  2. navigate into the crystal folder and manually invoked the Makefile by sudo make
  3. came to the root/ again and invoked the outer Makefile by sudo make

and this perfectly worked .

Question:

Why the child CMake is not getting invoked as I mentioned in the What isn't working section ???

Use target_link_libraries(thegame ${CRYSTAL_LIB_NAME}) in the root CMakeLists.txt and remove link_directories call. CMake will recognize that you are linking to crystal target and set makefile dependencies and compiler flags accordingly.

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