What makes a better constant in C, a macro or an enum?

In terms of readability, enumerations make better constants than macros, because related values are grouped together. In addition, enum defines a new type, so the readers of your program would have easier time figuring out what can be passed to the corresponding parameter. Compare #define UNKNOWN 0 #define SUNDAY 1 #define MONDAY 2 #define TUESDAY … Read more

Is there a way to use C++ preprocessor stringification on variadic macro arguments?

You can use various recursive macro techniques to do things with variadic macros. For example, you can define a NUM_ARGS macro that counts the number of arguments to a variadic macro: #define _NUM_ARGS(X100, X99, X98, X97, X96, X95, X94, X93, X92, X91, X90, X89, X88, X87, X86, X85, X84, X83, X82, X81, X80, X79, X78, … Read more

How to allow optional trailing commas in macros?

Make the comma optional As DK. points out, the trailing comma can be made optional. Rust 1.32 You can use the ? macro repeater to write this and disallow multiple trailing commas: ($Name:ident { $($Variant:ident),* $(,)? }) => { // ^^^^^ Previous versions This allows multiple trailing commas: ($Name:ident { $($Variant:ident),* $(,)* }) => { … Read more

How to pass macro definition from “make” command line arguments (-D) to C source code?

Call make command this way: make CFLAGS=-Dvar=42 And be sure to use $(CFLAGS) in your compile command in the Makefile. As @jørgensen mentioned , putting the variable assignment after the make command will override the CFLAGS value already defined the Makefile. Alternatively you could set -Dvar=42 in another variable than CFLAGS and then reuse this … Read more