nick
nick

Reputation: 47

How to build a one command compile project by cmake which have submodules?

I have a project like this:

(base) [tp]➜  ~ tree cmake_test
cmake_test
├── CMakeLists.txt
├── src
│   ├── CMakeLists.txt
│   └── mycode.cpp
├── sub1
│   ├── CMakeLists.txt
│   └── src
│       ├── CMakeLists.txt
│       └── somecode.cpp
└── sub2
    ├── CMakeLists.txt
    └── src
        ├── CMakeLists.txt
        └── somecode2.cpp

which i want to build a project cmake_test, it has two submodules - sub1 and sub2, and its own build target src

sub1 and sub2 are library maker, which means their build targets is some dll, then the src(mycode.cpp) part need this dll to build a executable file.

so, in the first CMakeLists.txt, i do like this:

cmake_minimum_required(VERSION 2.8)                                                                                                                   
project(cmake_test)
add_subdirectory(sub1 sub1_src)
add_subdirectory(sub2 sub2_src)
add_subdirectory(src my_src)

and in sub1/CMakeLists.txt:

cmake_minimum_required(VERSION 2.8)                                                                                                                   
project(sub1)
add_subdirectory(src sub1_src1)

and in sub1/src/CMakeLists.txt:

cmake_minimum_required(VERSION 2.8)                                                                                                                   
add_library(somecode SHARED somecode.cpp)
install(TARGETS somecode LIBRARY DESTINATION ${CMAKE_INSTALL_PREFIX})

src/CMakeLists.txt:

cmake_minimum_required(VERSION 2.8)

link_directories(${CMAKE_INSTALL_PREFIX})
add_executable(mycode mycode.cpp)
target_link_libraries(${arg1} somecode)
# please notice here, src need to link somecode.so
# somecode is built from sub1, and install to ${CMAKE_INSTALL_PREFIX}
# so the update somdecode.so is placed after install sub1)                                                                                                             
install(TARGETS mycode RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX})

the problem happens when i type: make install in cmake/build, because the compile order is:

sub1 make, sub2 make, src make, sub1 install, sub2 install, src install.

please notice src make is in front of sub1 install. so, if i modify the sub1 code, then this make install is bad, because mycode use the old sub1 code.

So, how can i make this work?

Upvotes: 0

Views: 403

Answers (1)

link_directories(${CMAKE_INSTALL_PREFIX})

You shouldn't need to do this. You should be able to just do:

target_link_libraries(mycode somecode)

and cmake knows that the mycode program requires the somecode library and it will automatically build somecode before it links mycode.

If this doesn't automatically happen, then something else is wrong with the CMakeLists. It might be because you wrote ${arg1} instead of mycode. Is arg1 a variable that contains the word mycode?

Upvotes: 3

Related Questions