How can I build a C++ project with multiple interdependent subdirectories?

前端 未结 2 1845
青春惊慌失措
青春惊慌失措 2020-12-22 15:55

I have a C++ project where I\'ve used directories as more of an organizational element -- the way one might use packages in Java or directories in PHP. Directories are not

2条回答
  •  猫巷女王i
    2020-12-22 16:29

    Since the directory structure in your project is just there to keep your files organized, one approach is to have a CMakeLists.txt that automatically finds all sources files in the src directory and also adds all directories as include directories that have a header file in them. The following CMake file may serve as a starting point:

    cmake_minimum_required(VERSION 3.0)
    
    project (Foo)
    
    file(GLOB_RECURSE Foo_SOURCES "src/*.cpp")
    file(GLOB_RECURSE Foo_HEADERS "src/*.h")
    
    set (Foo_INCLUDE_DIRS "")
    foreach (_headerFile ${Foo_HEADERS})
        get_filename_component(_dir ${_headerFile} PATH)
        list (APPEND Foo_INCLUDE_DIRS ${_dir})
    endforeach()
    list(REMOVE_DUPLICATES Foo_INCLUDE_DIRS)
    
    add_executable (FooExe ${Foo_SOURCES})
    target_include_directories(FooExe PRIVATE ${Foo_INCLUDE_DIRS})
    

    The two file(GLOB_RECURSE ... commands determine the set of source and header files. The foreach loop computes the set of include directories from the list of all header files.

    One drawback with computing the set of source files is that CMake will not automatically detect when new files are added to your source tree. You manually have to re-create your build files then.

提交回复
热议问题