Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C preprocessor: expand macro in a #warning

I would like to print a macro value (expand the macro) in the #warning directive.

For example, for the code:

#define AAA 17 #warning AAA = ??? 

The desired compile-time output would be

warning: AAA = 17 

What do I use for ???, or, how do I augment the code?

like image 804
elomage Avatar asked Sep 28 '12 09:09

elomage


People also ask

How are macros expanded in C?

The LENGTH and BREADTH are called the macro templates. The values 10 and 20 are called macro expansions. When the program run and if the C preprocessor sees an instance of a macro within the program code, it will do the macro expansion. It replaces the macro template with the value of macro expansion.

What is a preprocessor macro?

Macros allow you to write commonly used PL/I code in a way that hides implementation details and the data that is manipulated and exposes only the operations. In contrast with a generalized subroutine, macros allow generation of only the code that is needed for each individual use.

What is preprocessor expansion?

The preprocessor provides the ability for the inclusion of header files, macro expansions, conditional compilation, and line control. In many C implementations, it is a separate program invoked by the compiler as the first part of translation.


1 Answers

You can use the preprocessor directive #pragma message.

Example:

#define STR_HELPER(x) #x #define STR(x) STR_HELPER(x)  #define AAA 123 #pragma message "content of AAA: " STR(AAA)  int main() { return 0; } 

The output may look like this:

$ gcc test.c test.c:5:9: note: #pragma message: content of AAA: 123  #pragma message("content of AAA: " STR(AAA))          ^ 

For reference:

  • https://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html
  • https://msdn.microsoft.com/en-us/library/x7dkzch2.aspx
  • https://clang.llvm.org/docs/UsersManual.html#controlling-diagnostics-via-pragmas
like image 75
moooeeeep Avatar answered Nov 05 '22 11:11

moooeeeep