41

How do I set up CMake to recursively scan a given directory and determine the list of source files?

My project is a shared library. I have a folder structure similar to this:

/
  src/              # Source files in an arbitrary tree
  include/          # Headers, tree mirrors that of the src/ folder
  examples/         # Executable code examples that link against the library
  CMakeLists.txt

I want CMake to recursively scan src and include and determine the list of source and header files in my project, regardless of the directory structure. I also want to avoid:

  • Polluting the src/ and include/ directories with endless CMakeLists.txt files
  • Having to change and adapt the scripts every time I change my folder structure

It is fine for each example to have their own build script, however.

Matheus Moreira
  • 17,106
  • 3
  • 68
  • 107
  • Possible duplicate of [How to use all \*.c files in a directory with the Cmake build system?](https://stackoverflow.com/questions/2110795/how-to-use-all-c-files-in-a-directory-with-the-cmake-build-system) – BitShift Mar 16 '19 at 10:31
  • @Medicineman25, that question is about globbing a single directory. Mine is about globbing a whole tree and requires a recursive algorithm. – Matheus Moreira Mar 20 '19 at 02:09
  • that is true, although the answer is identical. – BitShift Mar 20 '19 at 02:17
  • @Medicineman25, the question, however, is not. While a recursive solution was posted, many of the possible duplicate's answers including the accepted answer are incompatible with my question. – Matheus Moreira Mar 20 '19 at 02:21
  • I've seen many questions marked as duplicate where the questions are different but the answers are ultimately the same. In that way SO encourages people to find the right question, not just the right answer. Although you are correct: the accepted answer is different so I'll leave it :) – BitShift Mar 20 '19 at 02:26

1 Answers1

42

CMake provides the following command for recursive files globing:

file(GLOB_RECURSE variable [RELATIVE path] 
   [FOLLOW_SYMLINKS] [globbing expressions]...)

Command documentation: http://www.cmake.org/cmake/help/v2.8.8/cmake.html#command:file

Renske
  • 98
  • 9
Andrey Kamaev
  • 29,582
  • 6
  • 94
  • 88
  • 13
    Note that if you use this method, you'll have to regenerate cmake again every time you add or remove source files. – mrgrieves Apr 02 '13 at 22:11
  • 8
    @mrgrieves is there a more efficient method? If so, please consider adding another answer to this question. – Matheus Moreira Oct 17 '14 at 23:05
  • 3
    This is a really bad example, because the file(GLOB_RECURSIVE) does not let you selectively choose the sub-directory. – user3696153 Apr 30 '18 at 04:40
  • 1
    @mrgrieves It was improved around 3.11, where CONFIGURE_DEPENDS flags allows to make globbing result a dependency to configure step. – kwesolowski Nov 19 '20 at 11:42