0

Provided my project is like this:

|--main.cpp
  |-A--a1.cpp
  |   |-a2.cpp
  |
  |-B--b1.cpp
      |-b2.cpp
|--CMakeLists.txt

How could I add all the *.cpp (e.g main.cpp, A/a1.cpp, A/a2.cpp, B/b1.cpp, B/b2.cpp) to a cmake variable SRC ? I hope I could only need one CMakeLists.txt. By the way, what if I need to exclude certain .cpps ?

coin cheung
  • 949
  • 2
  • 10
  • 25
  • 2
    Possible duplicate of [Automatically add all files in a folder to a target using CMake?](https://stackoverflow.com/questions/3201154/automatically-add-all-files-in-a-folder-to-a-target-using-cmake) – yadhu Oct 23 '18 at 12:37
  • 1
    Possible duplicate of [Add all files under a folder to a CMake glob?](https://stackoverflow.com/questions/35411489/add-all-files-under-a-folder-to-a-cmake-glob) – Tsyvarev Oct 23 '18 at 12:47

2 Answers2

2

As mentioned by Alexander, you can use file(GLOB_RECURSE myVar myRegex) to get all the files matching the myRegex into a myVar as a list. In order to exclude some you could play around with the myRegex, or you could filter the list with list(FILTER myVar <INCLUDE|EXCLUDE> REGEX <regular_expression>)

But note that adding another .cpp file to your project will not automatically be added to your target on rebuild. You will need to explicitly reconfigure your project for the changes to be made. Since CMake 3.12 there is also an option CONFIGURE_DEPENDS for file GLOBE and GLOBE_RECURSE, that will do the update on rebuild for you.

Here is the NOTE from CMake documentation:

Note We do not recommend using GLOB to collect a list of source files from your source tree. If no CMakeLists.txt file changes when a source is added or removed then the generated build system cannot know when to ask CMake to regenerate. The CONFIGURE_DEPENDS flag may not work reliably on all generators, or if a new generator is added in the future that cannot support it, projects using it will be stuck. Even if CONFIGURE_DEPENDS works reliably, there is still a cost to perform the check on every rebuild.

Bob Bills
  • 519
  • 4
  • 8
1

It's what you want:

file(GLOB_RECURSE SRC *.cpp)

For more info: https://cmake.org/cmake/help/v3.0/command/file.html

For excluding you can write function.

Note: But I don't recommend to use 'glob'. Better use 'set' with list of files.