Search code examples
c++visual-studiovisual-c++doctest

Unable to compile doctest's `CHECK_THROWS_AS` with Visual Studio 2019


Consider the following code using doctest.h C++ unit test library:

#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "doctest.h"
TEST_CASE("") {
    CHECK_THROWS_AS(throw 0, int);
}

The code creates a single test case with an empty name. The test ensures that throw 0 throws an exception of type int. The example compiles and runs successfully on GCC.

However, compiling with Visual Studio 2019 yields an error:

[REDACTED]>cl /std:c++17 a.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 19.29.30142.1 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

a.cpp
a.cpp(4): error C2062: type 'int' unexpected

How do I fix it?

At the same time, a simpler example compiles and works as expected:

#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "doctest.h"
TEST_CASE("") {
    CHECK(2 * 2 == 4);
}

Solution

  • Visual C++ command line compiler does not fully support C++ exceptions by default, see here. Hence, doctest disables them inside (_CPPUNWIND is left undefined by VS), but the error message is somewhat misleading.

    You should pass the /EHsc compiler flag:

    [REDACTED]>cl /EHsc /std:c++17 a.cpp
    Microsoft (R) C/C++ Optimizing Compiler Version 19.29.30142.1 for x64
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    a.cpp
    Microsoft (R) Incremental Linker Version 14.29.30142.1
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /out:a.exe
    a.obj
    

    As a sidenote, both Visual Studio's default "Empty project" and CMake configurations include this flag by default:

    enter image description here