The best way to specify sourcefiles in CMake is by listing them explicitly.
The creators of CMake themselves advise not to use globbing.
See: Filesystem
(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.)
Of course, you might want to know what the downsides are - read on!
When Globbing Fails:
The big disadvantage to globbing is that creating/deleting files won't automatically update the build system.
If you are the person adding the files, this may seem an acceptable trade-off. However, this causes problems for other people building your code; they update the project from version control, run build, and then contact you, complaining that
"the build's broken".
To make matters worse, the failure typically gives some linking error which doesn't give any hints to the cause of the problem and time is lost troubleshooting it.
In a project I worked on, we started off globbing, but we got so many complaints when new files were added that it was enough reason to explicitly list files instead of globbing.
This also breaks common Git workflows
(git bisect
and switching between feature branches).
So I couldn't recommend this. The problems it causes far outweigh the convenience. When someone can't build your software because of this, they may lose a lot of time to track down the issue or just give up.
And another note. Just remembering to touch CMakeLists.txt
isn't always enough. With automated builds that use globbing, I had to run cmake
before every build since files might have been added/removed since last building *.
Exceptions to the rule:
There are times where globbing is preferable:
- For setting up a
CMakeLists.txt
files for existing projects that don't use CMake.
it’s a fast way to get all the source referenced (once the build system's running - replace globbing with explicit file-lists).
- When CMake isn't used as the primary build system, if for example you're using a project who aren't using CMake, and you would like to maintain your own build-system for it.
- For any situation where the file list changes so often that it becomes impractical to maintain. In this case, it could be useful, but then you have to accept running
cmake
to generate build-files every time to get a reliable/correct build (which goes against the intention of CMake - the ability to split configuration from building).
*Yes, I could have written a code to compare the tree of files on disk before and after an update, but this is not such a nice workaround and something better left up to the build system.