Run ctest from different directory than build directory used by cmake?

Since CMake 3.20 ctest has the option --test-dir for exactly that.

--test-dir <dir> Specify the directory in which to look for tests.

For CMake older than 3.20:

I couldn’t find the way to do it through ctest options, but it is doable using the rule make test which is linked to ctest.

In the Makefile generated by cmake in your build folder you can find the rule:

#Special rule for the target test
test:
    @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running tests..."
    /usr/bin/ctest --force-new-ctest-process $(ARGS)
.PHONY : test

make provides the option that you want with -C /path/to/build_directory/, and you can add any ctest options with ARGS='your ctest options here'

For example, from any directory in your system you can write:

make test -C /path/to/build_folder ARGS='-R SpecificTestIWantToRun -VV'

or

cmake --build <bld_directory> --target test -- ARGS="<ctest_args>"

Another approach without make, is to use parenthesis in your terminal to create a subshell. This will execute the command without changing the folder of your current shell.

(cd $build_folder; ctest -V)

Leave a Comment