Real-world use of X-Macros

I discovered X-macros a couple of years ago when I started making use of function pointers in my code. I am an embedded programmer and I use state machines frequently. Often I would write code like this: /* declare an enumeration of state codes */ enum{ STATE0, STATE1, STATE2, … , STATEX, NUM_STATES}; /* declare … Read more

How do I see a C/C++ source file after preprocessing in Visual Studio?

cl.exe, the command line interface to Microsoft Visual C++, has three different options for outputting the preprocessed file (hence the inconsistency in the previous responses about Visual C++): /E: preprocess to stdout (similar to GCC’s -E option) /P: preprocess to file /EP: preprocess to stdout without #line directives If you want to preprocess to a … Read more

C++ preprocessor __VA_ARGS__ number of arguments

I usually use this macro to find a number of params: #define NUMARGS(…) (sizeof((int[]){__VA_ARGS__})/sizeof(int)) Full example: #include <stdio.h> #include <string.h> #include <stdarg.h> #define NUMARGS(…) (sizeof((int[]){__VA_ARGS__})/sizeof(int)) #define SUM(…) (sum(NUMARGS(__VA_ARGS__), __VA_ARGS__)) void sum(int numargs, …); int main(int argc, char *argv[]) { SUM(1); SUM(1, 2); SUM(1, 2, 3); SUM(1, 2, 3, 4); return 1; } void sum(int numargs, … Read more

Overloading Macro on Number of Arguments

Simple as: #define GET_MACRO(_1,_2,_3,NAME,…) NAME #define FOO(…) GET_MACRO(__VA_ARGS__, FOO3, FOO2)(__VA_ARGS__) So if you have these macros, they expand as described: FOO(World, !) // expands to FOO2(World, !) FOO(foo,bar,baz) // expands to FOO3(foo,bar,baz) If you want a fourth one: #define GET_MACRO(_1,_2,_3,_4,NAME,…) NAME #define FOO(…) GET_MACRO(__VA_ARGS__, FOO4, FOO3, FOO2)(__VA_ARGS__) FOO(a,b,c,d) // expands to FOO4(a,b,c,d) Naturally, if you … Read more

#pragma pack effect

#pragma pack instructs the compiler to pack structure members with particular alignment. Most compilers, when you declare a struct, will insert padding between members to ensure that they are aligned to appropriate addresses in memory (usually a multiple of the type’s size). This avoids the performance penalty (or outright error) on some architectures associated with … Read more

#define macro for debug printing in C?

If you use a C99 or later compiler #define debug_print(fmt, …) \ do { if (DEBUG) fprintf(stderr, fmt, __VA_ARGS__); } while (0) It assumes you are using C99 (the variable argument list notation is not supported in earlier versions). The do { … } while (0) idiom ensures that the code acts like a statement … Read more