What is the #error
directive in C? What is the use of it?
Asked
Active
Viewed 7.9k times
44
3 Answers
43
It's a preprocessor directive that is used (for example) when you expect one of several possible -D
symbols to be defined, but none is.
#if defined(BUILD_TYPE_NORMAL)
# define DEBUG(x) do {;} while (0) /* paranoid-style null code */
#elif defined(BUILD_TYPE_DEBUG)
# define DEBUG(x) _debug_trace x /* e.g. DEBUG((_debug_trace args)) */
#else
# error "Please specify build type in the Makefile"
#endif
When the preprocessor hits the #error
directive, it will report the string as an error message and halt compilation; what exactly the error message looks like depends on the compiler.

geekosaur
- 59,309
- 11
- 123
- 114
-
2Wouldn't it be more appropriate to say it halts preprocessing? I guess preprocessing can be viewed as a step in compilation, but it can definitely be done as a separate step, and is internally performed as a separate step, so it fails/reports a fatal error earlier on than a compilation error. – RastaJedi Apr 19 '16 at 19:57
15
I may have invalid code but its something like...
#if defined USING_SQLITE && defined USING_MYSQL
#error You cannot use both sqlite and mysql at the same time
#endif
#if !(defined USING_SQLITE && defined USING_MYSQL)
#error You must use either sqlite or mysql
#endif
#ifdef USING_SQLITE
//...
#endif
#ifdef USING_MYSQL
//...
#endif
-
the code works fine with this little correction #if !(defined USING_SQLITE || defined USING_MYSQL) – Alvpjh Sep 21 '20 at 18:49
4
If compiler compiles this line then it shows a compiler fatal error: and stop further compilation of program:
#include<stdio.h>
#ifndef __MATH_H
#error First include then compile
#else
int main(){
float a,b=25;
a=sqrt(b);
printf("%f",a);
return 0;
}
#endif
Output:compiler error --> Error directive :First include then compile

Nishant Kumar
- 5,995
- 19
- 69
- 95