5

I'm using doctest for the tests in my C++ project.

I would like to put the test code alongside my implementations, as the library says is possible, but I can't seem to figure out what to do with the doctest implementation code.

I have a doctest.cpp file that looks like this:

#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "doctest.h"

A main.cpp that looks like this:

#include "thing.h"

int main(int argc, const char *argv[]) {
    do_thing();
}

thing.h is self-explanatory, but thing.cpp looks like this:

do_thing() {}

TEST_CASE("Test thing") {
    CHECK(1 == 1);
}

CMake is used to create two executables, a Tests executable and a Main executable.

If I don't include doctest.cpp in my project sources for Main, I get undefined reference errors because it can't find a definition for all the testing stuff in doctest.

However, if I do include it I get errors because there are multiple main() functions in one target.

I can't find any info on this in the doctest documentation.

How are you meant to get around this?

Omegastick
  • 1,773
  • 1
  • 20
  • 35

2 Answers2

5

The author of the library gave a good response in this issue:

DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN implements the test runner and also defines a main() function.

DOCTEST_CONFIG_IMPLEMENT implements ONLY the test runner.

If you define your own main() then you should use DOCTEST_CONFIG_IMPLEMENT - have a look at the relevant docs.

You will need the test runner implemented in your main executable (that means doctest.cpp) since you are writing your tests alongside your production code.

You can also define DOCTEST_CONFIG_DISABLE when building the main executable so tests are written in the production code but aren't compiled (you will still need doctest.cpp so it all links). This way you won't need to #ifdef the tests.

You could also entirely remove the test executable and use the main executable for running the tests - docs.

I went with the first option of writing my own main() function.

Omegastick
  • 1,773
  • 1
  • 20
  • 35
2

I encountered the same problem and one workaround is to add -DDOCTEST_CONFIG_DISABLE to the compiler flags when you compile Main.

ttq
  • 383
  • 3
  • 7
  • But this effectively disable the tests. – Vinícius Ferrão Jul 15 '23 at 18:12
  • @Vinicius. Yes, I think that's the idea when compiling `Main`. One shouldn't include the option `-DDOCTEST_CONFIG_DISABLE ` when compiling `Tests`. The test suit is usually only executed for the latter (`Tests`), while the former (`Main`) compiles the actual program without the tests. – ttq Jul 16 '23 at 13:30