Is there a way to write a C preprocessor macro that expands to different things depending on what argument it receives?
#define foo() ???
/* 1 */
foo(name)
/* 2 */
foo(_)
Desired result:
/* 1 */
int name;
/* 2 */
/*ignore*/
Yes, I know macros are evil. I'm asking this mostly out of curiosity.
In this tutorial, you will be introduced to c preprocessors, and you will learn to use #include, #define and conditional compilation with the help of examples. Working of C Preprocessor. The C preprocessor is a macro preprocessor (allows you to define macros) that transforms your program before it is compiled.
(2) However, you cannot define a macro of a macro like #define INCLUDE #define STDH include <stdio. h> .
No, because C 2011 [N1570] 6.10. 3.4 3 says, about macro replacement, “The resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing directive even if it resembles one,…” Show activity on this post.
A conditional macro definition is a line of the form: target-list := macro = value. which assigns the given value to the indicated macro while make is processing the target named target-list and its dependencies.
To expand on Gavin Smith's answer, you actually can check conditions within a macro expansion:
#define FOO_name 1
#define FOO__ 0
#define CONC(a,b) a##_##b
#define IF(c, t, e) CONC(IF, c)(t, e)
#define IF_0(t, e) e
#define IF_1(t, e) t
#define FOO(x) IF(CONC(FOO,x), int x;, )
FOO(name) // -> int name;
FOO(_) // -> /*nothing*/
If you're feeling adventurous you can easily extend IF
to allow commas, suppress macro expansion, etc. with helper macros.
As above though this does require that you know all of the desired names in advance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With