How to add source files in another folder

前端 未结 1 1245
后悔当初
后悔当初 2021-02-08 15:41

I\'m using cmake to build my project in C++. Assume I have the following directories on my Source folder

Source
  |_Dir1
  |   |_Class.cpp
  |   |_Class.hpp
  |
         


        
1条回答
  •  清歌不尽
    2021-02-08 16:34

    Supposed you have a single CMakeLists.txt file at the Source directory, you'll create two variables using different file() commands

    file(GLOB Dir1_Sources RELATIVE "Dir1" "*.cpp")
    file(GLOB Dir2_Sources RELATIVE "Dir2" "*.cpp")
    

    and add both sets generated by the file() commands to your target's source list:

    add_executable(MyProgram ${Dir1_Sources} ${Dir2_Sources})
    

    Alternatively you can place a CMakeLists.txt file under Dir1 and Dir2 (Main) looking as follows

    Source
        |
        |_ CMakeLists.txt   
        |    > project(MyProgram)
        |    > cmake_minimum_required(VERSION 3.8)
        |    > add_subdirectory("Dir1")
        |    > add_subdirectory("Dir2")
        |
        |_ Dir1   
        |     |_ CMakeLists.txt   
        |         > file(GLOB Sources "*.cpp")
        |         > add_library(Dir1 STATIC ${Sources})
        |_ Dir2   
              |_ CMakeLists.txt   
                  > file(GLOB Sources "*.cpp")
                  > add_executable(MyProgram ${Sources})
                  > target_link_libraries(MyProgram Dir1)
    

    to add subdirectories as further (static) libraries linked to your main target.

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