views:

460

answers:

3

Hello. Is is possible to print to stderr the value of a preprocessor variable in C? For example, what I have right now is:

#define PP_VAR (10)
#if (PP_VAR > 10)
    #warning PP_VAR is greater than 10
#endif

But what I'd like to do is:

#define PP_VAR (10)
#if (PP_VAR > 10)
    #warning PP_VAR=%PP_VAR%
#endif

Is something like this possible in C?

A: 

Well, what you are doing is actually non-standard. Firstly, the "#warning" or "#warn" directive is not standard. Secondly, when using the preprocessor, the line must begin with the pound symbol, without any spaces:

#ifdef BLAH1
#    define BLAH2 // OK, because pound is at the very left.
#endif

#ifdef BLAH3
     #define BLAH4 // Works on many compilers, but is non-standard.
#endif

Since you are already using a non-standard extension, you will need to look up the documentation of the particular preprocessor/compiler that you are using to see what it says about "#warning".

Michael Aaron Safyan
Your second point is not correct - C89 lifted that restriction. The # must be the first symbol on the line, but it may be preceded by white space (but not by comments).
Jonathan Leffler
Thanks. I can't believe I'm still living in the dark ages. Can you point me to the relevant document for that?
Michael Aaron Safyan
Wow. I came later to the game than I thought - I never knew about that restriction at all.
Michael Kohne
+1  A: 

Use the preprocessor token-pasting operator: ##TOKEN_NAME

As previously noted, the preprocessor directives you are using are non-standard, so YMMV.

rtenhove
+2  A: 

Many C compilers support #warning (but it is not defined by the C standard).

However, GCC at least does not do pre-processing on the data that follows, which means it is hard to see the value of a variable.

#define PP_VAR 123
#warning "Value of PP_VAR = " PP_VAR
#warning "Value of PP_VAR = " #PP_VAR
#warning "Value of PP_VAR = " ##PP_VAR

GCC produces:

x.c:2:2: warning: #warning "Value of PP_VAR = " PP_VAR
x.c:3:2: warning: #warning "Value of PP_VAR = " #PP_VAR
x.c:4:2: warning: #warning "Value of PP_VAR = " ##PP_VAR
Jonathan Leffler