C Preprocessor, Stringify the result of a macro

Like this: #include <stdio.h> #define QUOTE(str) #str #define EXPAND_AND_QUOTE(str) QUOTE(str) #define TEST thisisatest #define TESTE EXPAND_AND_QUOTE(TEST) int main() { printf(TESTE); } The reason is that when macro arguments are substituted into the macro body, they are expanded unless they appear with the # or ## preprocessor operators in that macro. So, str (with value TEST … Read more

Is the C99 preprocessor Turing complete?

Well macros don’t directly expand recursively, but there are ways we can work around this. The easiest way of doing recursion in the preprocessor is to use a deferred expression. A deferred expression is an expression that requires more scans to fully expand: #define EMPTY() #define DEFER(id) id EMPTY() #define OBSTRUCT(…) __VA_ARGS__ DEFER(EMPTY)() #define EXPAND(…) … Read more

The role of #ifdef and #ifndef

Text inside an ifdef/endif or ifndef/endif pair will be left in or removed by the pre-processor depending on the condition. ifdef means “if the following is defined” while ifndef means “if the following is not defined”. So: #define one 0 #ifdef one printf(“one is defined “); #endif #ifndef one printf(“one is not defined “); #endif … Read more

Pragma in define macro

If you’re using c99 or c++0x there is the pragma operator, used as _Pragma(“argument”) which is equivalent to #pragma argument except it can be used in macros (see section 6.10.9 of the c99 standard, or 16.9 of the c++0x final committee draft) For example, #define STRINGIFY(a) #a #define DEFINE_DELETE_OBJECT(type) \ void delete_ ## type ## … Read more