【问题标题】:How to detect which (C++) language standard was selected in the Project->General Properties->C++ Language Standard [duplicate]如何检测在项目->常规属性->C++语言标准中选择了哪个(C++)语言标准[重复]
【发布时间】:2022-01-15 10:12:27
【问题描述】:

我正在使用 Visual Studio 2019 进行开发,并且希望能够根据所选的语言标准(C++20、C++17)有条件地编译我的 C++ 程序等)来自项目属性 -> 常规属性 -> C++ 语言标准。 例如,当我设置它 C++20 时会定义什么,以便我可以将其用作:

#ifdef WHAT_DO_I_PUT_HERE_FOR_C++_20 
#else
#ifdef WHAT_DO_I_PUT_HERE_FOR_C++_17
...

【问题讨论】:

  • @jpo38 似乎不适用于条件编译。
  • 为什么?看我的回答,它肯定适用于条件编译。
  • @jpo378 _HAS_CXX17 或 _HAS_CXX20 似乎可以工作,但它们是标准的吗?
  • 不知道,这可能只能由 Visual Studio 设置。我的回答中提出的__cplusplus 应该适用于所有编译器。

标签: c++ visual-c++ c++17 visual-studio-2019 c++20


【解决方案1】:

这应该可行:

#if (__cplusplus >= 202002L)
    // C++20 (or later) code
#elif (__cplusplus == 201703L) 
    // C++17 code
#else
    // C++14 or older code
#endif

【讨论】:

  • 很遗憾,它不适用于 Visual Studio 2019 版本 16.10.4 感谢您的意见
  • @Vectorizer 这将是 Visual Studio 的一个合规缺陷,并且是一个非常大的缺陷。
  • @DevSolar:也许我错过了什么。我所做的只是将 C++ 语言标准设置为 C++17,并期望代码的相关部分处于活动状态。
  • @Vectorizer:Set /Zc to enable updated __cplusplus macro.。抱歉,我自己不知道。
  • @DevSolar:感谢您在我离线时提供的帮助 ;-)!
【解决方案2】:

您可以使用 MSVC predefined macro _MSVC_LANG:

#ifndef VT_CPP_VERSION
# if defined (_MSVC_LANG)
#  define VT_CPP_VERSION _MSVC_LANG
# else
#  define VT_CPP_VERSION __cplusplus
# endif
#endif

#if defined (VT_CPP_VERSION)
# if   (VT_CPP_VERSION >= 202002L)
  // 20 or above
# elif (VT_CPP_VERSION >= 201703L)
  // 17
# elif (VT_CPP_VERSION >= 201402L)
  // 14
# elif (VT_CPP_VERSION >= 201103L)
  // 11
# else
  // cry.
# endif
#endif

如果你需要在代码已经编译完成后获取这个值(例如:共享库),那么你可以使用一个函数。

[[maybe_unused]] long version_used() noexcept {
#if defined (_MSVC_LANG)
  return _MSVC_LANG;
#else
  return __cplusplus;
#endif
}

【讨论】:

    猜你喜欢
    • 2011-07-24
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    • 2021-01-28
    • 2020-10-20
    • 2016-02-29
    相关资源
    最近更新 更多