如何正确设置_MSVC_LANG值?

san*_*ser 5 c++ visual-c++ c++17 visual-studio-2019

您可能知道_MSVC_VALUE,确定是否设置宏_HAS_CXX17_HAS_CXX20今天我尝试在Visual Studio 2019(最新16.6.4版本)中编译以下代码:

#include <algorithm>
#include <execution>
#include <vector>

int main()
{
    std::vector<int> _vector = { 3, 2, 1 };
    std::sort(std::execution::par, _vector.begin(), _vector.end());
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,它会抛出错误。例如这个: C3083 'execution': the symbol to the left of a '::' must be a type

当我查看<execution>头文件时,我注意到它无法编译,因为宏_HAS_CXX17设置为 0。

#if !_HAS_CXX17
#pragma message("The contents of <execution> are available only with C++17 or later.")
#else // ^^^ !_HAS_CXX17 / _HAS_CXX17 vvv
Run Code Online (Sandbox Code Playgroud)

然后我查看了vcruntime.h_HAS_CXX17文件中宏的定义:

#if !defined(_HAS_CXX17) && !defined(_HAS_CXX20)
    #if defined(_MSVC_LANG)
        #define _STL_LANG _MSVC_LANG
    #elif defined(__cplusplus) // ^^^ use _MSVC_LANG / use __cplusplus vvv
        #define _STL_LANG __cplusplus
    #else  // ^^^ use __cplusplus / no C++ support vvv
        #define _STL_LANG 0L
    #endif // ^^^ no C++ support ^^^

    #if _STL_LANG > 201703L
        #define _HAS_CXX17 1
        #define _HAS_CXX20 1
    #elif _STL_LANG > 201402L
        #define _HAS_CXX17 1
        #define _HAS_CXX20 0
    #else // _STL_LANG <= 201402L
        #define _HAS_CXX17 0
        #define _HAS_CXX20 0
    #endif // Use the value of _STL_LANG to define _HAS_CXX17 and _HAS_CXX20

    #undef _STL_LANG
#endif // !defined(_HAS_CXX17) && !defined(_HAS_CXX20)
Run Code Online (Sandbox Code Playgroud)

令我惊讶的是 的值_MSVC_LANG设置为201402L。应该会高很多。我-std=c++17像这个答案一样设置了编译标志。是的,这就是我的答案,事实证明它在五月份就有效了。

我尝试自己为宏定义正确的值,但它们被忽略或者引发一些其他错误:

#define _MSVC_LANG 201704L

// same code as before
// result: macro is ignored, no change
Run Code Online (Sandbox Code Playgroud)
#define _HAS_CXX17 1
#define _HAS_CXX20 1

// same code as before
// result: 250+ errors like this one:
// E0457    "basic_string_view" is not a function or static data member
Run Code Online (Sandbox Code Playgroud)

就在更新之前,我从这里安装了标准库的单独版本。海湾合作委员会 10.1.0。版本,我把它mingw/bin放在Windows 10中的系统路径中。

我不知道安装 gcc 可能会破坏 msvc 编译器。那么可能是VS 2019更新到16.6.4版本导致的?

我也看过这个问题,但没有任何帮助。

  • 有人可以报告类似的问题吗?
  • 有谁知道如何修复此问题并使用 VS 2019 版本 16.6.4 在 C++17 下编译代码?

san*_*ser 4

对于未来的读者:

如果您遇到类似问题,请仔细检查您是否正在更改随后将运行的配置。就我而言,我正在更改发布的所有设置,但我尝试运行调试配置,但不知何故我没有注意到它。

更改配置的步骤:

  • 右键单击项目
  • 左上角有一个下拉菜单
  • 选择您正在运行的相同配置