2016年8月5日 星期五

C程式 - X-Macro

Trace code 時看到類似用法,覺得很特別,做一下筆記

X-Macro 是一個可以在compile time 去對類似架構程式做簡化的寫法



X Macro is a technique in the C programming language for generating repeating code structures at compile time. It is used when the same operation has to be executed for a list of items, but regular for loops cannot be used.
Usage of X Macros dates back to 1960's.[1] It remains useful also in modern-day C, but is nevertheless relatively unknown.[2] [3]



An X-macro consists of two parts: the list, and the execution of the list. The list is just a #define construct which generates no code by itself. The execution of the list provides another #define macro, which is expanded for each entry in the list.




This example defines a list of variables, and automatically generates their declarations and a function to print them out.
First the list definition. The list entries could contain multiple arguments, but here only the name of the variable is used.
#define LIST_OF_VARIABLES \
    X(value1) \
    X(value2) \
    X(value3)

Then we execute this list to generate the variable declarations:
#define X(name) int name;
LIST_OF_VARIABLES
#undef X
In a similar way, we can generate a function that prints the variables and their names:
void print_variables()
{
#define X(name) printf(#name " = %d\n", name);
LIST_OF_VARIABLES
#undef X
}
When run through the C preprocessor, the following code is generated. Line breaks have been added for ease of reading, even though they are not actually generated by the preprocessor:
int value1;
int value2;
int value3;

void print_variables()
{
    printf("value1" " = %d\n", value1);
    printf("value2" " = %d\n", value2);
    printf("value3" " = %d\n", value3);
}


以上內容來自 <http://en.wikipedia.org/wiki/X_Macro



參考

沒有留言:

張貼留言