Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#error directive in C. How to display some #define

Tags:

c

debugging

I need to display some relevant information in #error preprocessor directive. For example:

#define myConstant 5

#if myConstant > 10
    #error myConstant has to be > 10, now %d  //should display "5"
#endif

How can I do that?

like image 807
Ivan Kryvosheia Avatar asked Aug 22 '19 11:08

Ivan Kryvosheia


1 Answers

You can't. #error doesn't allow/support that.

Instead, use _Static_assert, from C11:

#define myConstant 5

#define STRINGIFY(x) STRINGIFY_(x)
#define STRINGIFY_(x) #x
_Static_assert(myConstant > 10, "myConstant has to be > 10, now " STRINGIFY(myConstant));

Output:

test.c:5:1: error: static assertion failed: "myConstant has to be > 10, now 5"
 _Static_assert(myConstant > 10, "myConstant has to be > 10, now " STRINGIFY(myConstant));
 ^~~~~~~~~~~~~~
like image 118
S.S. Anne Avatar answered Sep 21 '22 01:09

S.S. Anne