How to add source files in another folder

2019-01-25 14:02发布

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
  |
  |_Dir2
      |_Main.cpp

In Dir1 there's a class with its header and implementation files (Class.cpp and Class.hpp).

In Dir2 there's the main application which uses the class in Dir1

What is the good way to tell the CMakeLists in Dir2 to build the executable with Dir1/Class.cpp file?

EDIT: To be more specific, I want to define that the source file for Class.cpp has to be used in Dir1's CMakeLists.txt, and not in Dir2's. Doing it the other way feels plain wrong to me and it's hard to use, so if there's a reason they're enforcing me to do this some clarification on the topic would be nice.

What I'm currently doing is hard-coding the Class.cpp file location in Dir2/CMakeLists.txt but that just doesn't scale when I've got a bunch of classes interacting together.

标签: cmake
1条回答
爷的心禁止访问
2楼-- · 2019-01-25 14:47

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.

查看更多
登录 后发表回答