【问题标题】:Feature test macros not working properly in Visual C++功能测试宏在 Visual C++ 中无法正常工作
【发布时间】:2018-08-25 06:50:43
【问题描述】:

在 Visual Studio 中测试功能时,我发现了这种奇怪的行为:

#ifndef __cpp_constexpr
#error Opposite day! //Compiler error
#endif

#define test_macro

#ifndef test_macro
#error But only for feature macros? //No compiler error
#endif

int main() {}

__cpp_constexpr明确定义的,我在实际程序中使用它。 根据我的测试,似乎使用功能宏 #ifndef 的行为类似于 #ifdef 反之亦然。

这是 Visual Studio 的错误,还是我遗漏了什么?

在 VS 2017、Visual C++14 或更高版本中编译,启用了 C++17 标准。

附: Intellisense 正在按预期工作,它只是编译器。

【问题讨论】:

  • FWIW 功能测试宏似乎也没有被其他编译器正确支持;例如,虽然 GCC 可以很好地处理 __cpp_constexpr,但它无法处理其他问题,例如 __cpp_lib_make_unique。实际上,它们似乎不可靠,因此并不适用于所有意图和目的。

标签: c++ visual-studio visual-c++ macros


【解决方案1】:

您使用了不正确的预定义宏和 pre-proc 代码。下一个代码可以提供帮助:

#if defined(__GNUG__) && (__cplusplus > 201103L)
#  define HAS_CONSTEXPR
#elif defined(_MSC_VER) && (_MSC_FULL_VER >= 190024210)
#  define HAS_CONSTEXPR
#endif // __GNUG__

#ifndef HAS_CONSTEXPR
#  error Opposite day! //Compiler error
#else
#   define test_macro
#   ifndef test_macro // useless by why not ? 
#     error But only for feature macros? //No compiler error
#   endif
#endif

建议使用 boost 配置库。它是交叉编译器,你可以这样解决它:

#ifdef BOOST_NO_CXX11_CONSTEXPR
#   error Opposite day! //Compiler error
#endif

它适用于 boost 支持的所有编译器(根据 boost 许可证,您可以检查源代码并在您的项目中进行复制)

【讨论】:

  • 我总是可以测试 Visual c++ 版本,但这不是跨平台的。很确定feature test macros 就是因为这个原因才被引入的。我也不能使用 boost。
  • @andreasxp 功能测试宏很好。但是“很难使用某些东西,你的编译器不支持女巫”(c)Jeff Alger :) 我已经完成了 gcc 的更新
  • @andreasxp __cplusplus 宏在 MSVC++ 中没有正确定义(我不知道为什么),所以你必须使用 _MSC_FULL_VER 检查
  • @VictorGubin 因为他们在技术上还没有“完整”的 C++11 支持 - 请参阅这篇博文了解详细信息:blogs.msdn.microsoft.com/vcblog/2018/04/09/…
猜你喜欢
  • 2018-08-20
  • 2017-09-23
  • 2015-07-05
  • 2023-04-01
  • 1970-01-01
  • 2013-11-06
  • 2013-10-29
  • 1970-01-01
相关资源
最近更新 更多