CTest --build-and-test ignores binary directory if source directory contains CMakeCache.txt
Problem
ctest --build-and-test
ignores the given binary directory if the source directory contains a CMakeCache.txt.
Example
I have a repository, which main project builds a library. It also includes code examples which link against that library. It looks a bit like this:
.
├── CMakeLists.txt
├── example
│ └── CMakeLists.txt
These code examples are build (and later run) in isolated subdirectories in the projects binary directory as part of the test suite using something along the lines of:
add_test(NAME ${TEST_FULL_NAME}
COMMAND ${CMAKE_CTEST_COMMAND}
--build-and-test ${TEST_SRC_DIR} ${TEST_BIN_DIR}
--build-generator ${CMAKE_GENERATOR}
--build-options ...
)
set_tests_properties(${TEST_FULL_NAME}
PROPERTIES
WORKING_DIRECTORY "${TEST_BIN_DIR}")
This works fine until a user runs cmake .
in example/
to test a local installation or directly from the build directory.
The result is the following (simplified):
.
├── CMakeLists.txt
├── example
│ ├── CMakeCache.txt <<<
│ └── CMakeLists.txt
From that moment on, running ctest of the main project will result in the above test failing.
The error messages are highly cryptic (often referring to unrelated directories) and essentially impossible for a CMake novice to understand.
It reconfigures the binary directory in example/
using the provided options, which often conflict with previous options as it often still refers to old library config files. If the build goes through, tests run in the source directory, but output files are still written to the working directory. All very confusing to debug.
Removing example/CMakeCache.txt
resolves the issue.