C语言#error命令,阻止程序编译

#error 指令用于在编译期间产生错误信息,并阻止程序的编译,其形式如下:

#error error_message

例如,我们的程序针对Linux编写,不保证兼容Windows,那么可以这样做:

#ifdef WIN32
#error This programme cannot compile at Windows Platform
#endif

WIN32 是Windows下的预定义宏。当用户在Windows下编译该程序时,由于定义了WIN32这个宏,所以会执行#error命令,提示用户发生了编译错误,错误信息是:

This programme cannot compile at Windows Platform

这和发生语法错误的效果是一样的,程序编译失败。请看下面的截图:

需要注意的是:报错信息不需要加引号" ",如果加上,引号会被一起输出。例如将上面的#error命令改为:  

#error "This programme cannot compile at Windows Platform"

那么错误信息如下:

再如,当我们希望以C++的方式来编译程序时,可以这样做:

#ifndef __cplusplus
#error 当前程序必须以C++方式编译
#endif   

posted on 2022-05-06 18:18  朴素贝叶斯  阅读(360)  评论(0编辑  收藏  举报

导航