proper way to define a dedicated target to build (and run) tests.

I’m working on a fairly large project with many sub-components (libraries, executables, associated tests). Right now, the ALL target includes everything, so a typical workflow involves config, build, and test stages, roughly mapping to cmake, make, make tests commands.

Is there a recommended way to split the build step into two parts, such that test executables are only built in a secondary stage ? I’m essentially looking for a way to have a streamlined build command that would build only the main targets and its dependencies, and then let the test target not only run the already compiled tests, but actually include the compilation ?

I’m aware of the EXCLUDE_FROM_ALL property, but am unsure of how to use that properly, or rather, how to introduce a new target that depends on all test executables, such that making that will do the right thing.

Are there any recipes for such a use-case ?


Why couldn’t you just use make MyMainTarget or, cmake --build . --target MyMainTarget?

Use add_custom_target and add_dependencies. You make your new tests target dependent on all the test executables. Building tests would then cause all the test executables to build.

because I have many targets that I want to build, just not the tests. (In fact, I may want to build whatever is then packaged and deployed, while building the tests only when I also want to run my test suite.)

Thanks. While that works indeed, I then need to manually add all my test executables as dependencies to my custom target, which is laborious and error-prone. I was hoping that there was a “standard” way of achieving the same thing. Or in fact, that the existing test targets (those defined by add_test and its variants), would itself depend on the test executables, making or updating them upon invocation of make test if they don’t exist yet.