How does #error in C/C++ work?

2019-03-14 15:42发布

I am guessing from # that it is only a compile-time utility. How can it be used in C/C++ programs?

Did not find much about it on the internet. Any links would be helpful.

3条回答
ゆ 、 Hurt°
2楼-- · 2019-03-14 15:59

It causes the compiler (or preprocessor) to output the error message. In C++, it also renders the translation unit ill-formed (i.e., it causes compilation to fail).

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.

It can also be useful if you want to be sure that some block of code is never compiled (for whatever reason).

查看更多
Evening l夕情丶
3楼-- · 2019-03-14 15:59

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

In particular:

The directive #error causes the preprocessor to report a fatal error. The tokens forming the rest of the line following #error are used as the error message.

See also this question about the portability of these directives.

查看更多
Summer. ? 凉城
4楼-- · 2019-03-14 16:07

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
查看更多
登录 后发表回答