简体   繁体   English

C / C ++中的#error如何工作?

[英]How does #error in C/C++ work?

I am guessing from # that it is only a compile-time utility. 我从#中猜测它只是一个编译时实用程序。 How can it be used in C/C++ programs? 如何在C / C ++程序中使用它?

Did not find much about it on the internet. 在互联网上找不到太多有关它的信息。 Any links would be helpful. 任何链接都将有所帮助。

It causes the compiler (or preprocessor) to output the error message. 它使编译器(或预处理器)输出错误消息。 In C++, it also renders the translation unit ill-formed (ie, it causes compilation to fail). 在C ++中,它还会使翻译单元格式错误(即,导致编译失败)。

If you have several macros that could be defined and you want to be sure that only certain combinations of them are defined, you can use #error to cause compilation to fail if an invalid combination is defined. 如果可以定义多个宏,并且要确保仅定义了它们的某些组合,则可以使用#error如果定义了无效的组合,则会导致编译失败。

It can also be useful if you want to be sure that some block of code is never compiled (for whatever reason). 如果您要确保某些代码块永远不会编译(无论出于何种原因),它也很有用。

Useful to check compiler settings as well as verifying macro value combinations. 对检查编译器设置以及验证宏值组合很有用。 Some random examples: 一些随机的例子:

#if !defined(_DLL)
#  error This code will only work properly when compiled with /MD
#endif

#if _WIN32_WINNT < 0x502
#  error Sorry, Windows versions prior to XP SP2 are not supported
#endif

#if defined(_APPLE) && defined(_LINUX)
#  error Conflicting operating system option selected, choose one.
#endif

Here is a link to the documentation of the Gnu preprocessor explaining the #error and #warning directives: http://gcc.gnu.org/onlinedocs/cpp/Diagnostics.html 这是Gnu预处理程序文档的链接,解释了#error#warning指令: http : //gcc.gnu.org/onlinedocs/cpp/Diagnostics.html

In particular: 特别是:

The directive #error causes the preprocessor to report a fatal error. 指令#error使预处理器报告致命错误。 The tokens forming the rest of the line following #error are used as the error message. 构成#error的其余行的标记用作错误消息。

See also this question about the portability of these directives. 另请参阅有关这些指令的可移植性的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM