3

With CMake I try to execute a simple test using CTest. I have this configuration all in one directory (${CMAKE_SOURCE_DIR}):

~$ cat hello.cpp
#include <iostream>

int main() {
    std::cout << "hello world\n";
    return(0);
}

~$ cat CMakeLists.txt
cmake_minimum_required(VERSION 3.18)
project(TEST_CTEST)

enable_testing()
add_executable(test_ctest hello.cpp)
add_test(my_test ./build/test_ctest)

Then I execute:

~$ rm -rf Testing/ build/
~$ cmake -S . -B build
~$ cmake --build build
~$ ./build/test_ctest
hello world

~$ ctest
*********************************
No test configuration file found!
*********************************
Usage

  ctest [options]

The only hint I have found in other Q&A is to place enable_testing() into the root CMakeLists.txt. I feel like I just missed a little thing, but I can't find what.

How do I run a test with CTest?

Ingo
  • 588
  • 9
  • 21
  • 1
    You need to call `ctest` from **build** directory. Exactly this directory contains configuration file which `ctest` wants to read. – Tsyvarev Aug 26 '21 at 17:46
  • @Tsyvarev As I feared it is only a minor matter... Please make your comment an answer. I will accept it. – Ingo Aug 26 '21 at 18:53

1 Answers1

6

The macro enable_testing() creates ctest configuration file in the build directory. For find this file, ctest needs to be run from that build directory.

Running ctest from the source directory has no sense, as it doesn't see results of CMake (unless you do in-source builds).

Tsyvarev
  • 60,011
  • 17
  • 110
  • 153
  • 2
    "unless you do in-source builds"... which you absolutely should not. – Alex Reinking Aug 26 '21 at 19:51
  • Starting with CMake 3.20, you can also run `ctest --test-dir /path/to/tests` according to another question: https://stackoverflow.com/questions/38644741/run-ctest-from-different-directory-than-build-directory-used-by-cmake – sage Dec 15 '22 at 00:45