Friday, October 29, 2021

[SOLVED] Force serial execution for specific targets in CMake

Issue

In my CMake project I have several targets which simply run a certain set of unit tests (for example, runTestsForA, runTestsForB and runTestsForC). I also have a target, tests, that depends on all of these unit test targets, so I can run them with a single command.

I'm using CLion is my IDE, which tries to use parallel make builds by default (which I want and am also doing on the Continuous Integration server). However, it looks like the tests are running in parallel too now and some tests are not made for this (they use a local loopback to do some magic with sockets), which causes them to fail.. sometimes.

That is why I would like to force serial execution for some/all of the dependencies of my tests target. Unfortunately the CMake documentation did not help me, when I was searching information on how to do this. Which brings me to my questions: is this at all possible and how can it be done if it is?


Solution

Instead of manual tests target declaration you can use CTest tool. Use add_test command to create test targets, then CMake will automatically create tests target that will run all tests:

enable_testing()
add_test(NAME TestsForA COMMAND <command>)
add_test(NAME TestsForB COMMAND <command>)
set_tests_properties(TestsForA TestsForB  PROPERTIES RUN_SERIAL TRUE)

After that you can run make tests or ctest -j8 . in your build tree. The tests will be serialized.

More information can be found at:



Answered By - jet47