无法使用 Visual Studio 2019 编译 doctest 的 `CHECK_THROWS_AS`
Unable to compile doctest's `CHECK_THROWS_AS` with Visual Studio 2019
使用 doctest.h
C++ 单元测试库考虑以下代码:
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "doctest.h"
TEST_CASE("") {
CHECK_THROWS_AS(throw 0, int);
}
代码创建了一个空名称的测试用例。该测试确保 throw 0
抛出类型 int
的异常。该示例在 GCC 上编译并成功运行。
但是,使用 Visual Studio 2019 编译会产生错误:
[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
我该如何解决?
同时,一个更简单的示例按预期编译和工作:
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "doctest.h"
TEST_CASE("") {
CHECK(2 * 2 == 4);
}
默认情况下,Visual C++ 命令行编译器不完全支持 C++ 异常,请参阅 here. Hence, doctest disables them inside (_CPPUNWIND
is left undefined by VS), but the error message is somewhat misleading。
您应该传递 /EHsc
编译器标志:
[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
作为旁注,Visual Studio 的默认“空项目”和 CMake configurations 默认都包含此标志:
使用 doctest.h
C++ 单元测试库考虑以下代码:
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "doctest.h"
TEST_CASE("") {
CHECK_THROWS_AS(throw 0, int);
}
代码创建了一个空名称的测试用例。该测试确保 throw 0
抛出类型 int
的异常。该示例在 GCC 上编译并成功运行。
但是,使用 Visual Studio 2019 编译会产生错误:
[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
我该如何解决?
同时,一个更简单的示例按预期编译和工作:
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "doctest.h"
TEST_CASE("") {
CHECK(2 * 2 == 4);
}
默认情况下,Visual C++ 命令行编译器不完全支持 C++ 异常,请参阅 here. Hence, doctest disables them inside (_CPPUNWIND
is left undefined by VS), but the error message is somewhat misleading。
您应该传递 /EHsc
编译器标志:
[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
作为旁注,Visual Studio 的默认“空项目”和 CMake configurations 默认都包含此标志: