Multiple source directories for one executable with CMake

前端 未结 3 765
[愿得一人]
[愿得一人] 2020-12-19 15:29

I want my source organised in a number of subdirectories but be able to create a single executable without having to build a library for each subdirectory. Can CMake do this

相关标签:
3条回答
  • 2020-12-19 15:59

    Another (arguably better for big code bases) variant is to use a separate CMakeLists.txt for each sub-directory where you isolate adding sources of the directory to a target using target_sources and maybe some particular configuration settings \ include conditions for those sources:

    target_sources( SomeExeOrLib PRIVATE source1.h source1.cpp )
    

    here you also have more control of the scope by specifying PRIVATE, other options are INTERFACE or PUBLIC. See details here: https://cmake.org/cmake/help/v3.3/command/target_sources.html

    0 讨论(0)
  • 2020-12-19 16:12

    Here the my simple example

    cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
    project(foo CXX)
    # get all *.cpp files recursively
    file(GLOB_RECURSE SRC_FILES ${PROJECT_SOURCE_DIR}/*.cpp)
    add_executable(foo ${SRC_FILES})
    
    0 讨论(0)
  • 2020-12-19 16:16

    Yes, that would work.

    Update: What follows is not very relevant anymore because nowadays CMake supports response files, so there shouldn't be problems with too long command lines.

    However you might have troubles when the number of files get too high, and the command line too long for your compiler to be able to handle it. A possible solution is to add a static library for each subdirectory, add them to a list "ALL_MY_SUB_LIBS", and link them to the main target foo in this way:

    target_link_libraries(foo "-Wl,--whole-archive") #like opening a parenthesis
    target_link_libraries(foo ${ALL_MY_SUB_LIBS}) 
    target_link_libraries(foo "-Wl,--no-whole-archive") #like closing a parenthesis
    

    ld linker question: the --whole-archive option

    0 讨论(0)
提交回复
热议问题