请输入您要查询的百科知识:

 

词条 X Macro
释义

  1. Implementation

  2. Example

  3. Further reading

  4. References

X Macros are a technique for reliable maintenance of parallel lists, of code or data, whose corresponding items must appear in the same order. They are most useful where at least some of the lists cannot be composed by indexing, such as compile time.

Examples of such lists particularly include initialization of arrays, in concert with declarations of enumeration constants and function prototypes, generation of statement sequences and switch arms, etc.

Usage of X Macros dates back to the 1960s.[1] It remains useful also in modern-day C and C++ programming languages, but remains relatively unknown.[2]

[3]

Implementation

An X macro application consists of two parts:

  1. The definition of the list's elements.
  2. Expansion(s) of the list to generate fragments of declarations or statements.

The list is defined by a macro or header file (named, LIST) which generates no code by itself, but merely consists of a sequence of invocations of a macro (classically named "X") with the elements' data. Each expansion of LIST is preceded by a definition of X with the syntax for a list element. The invocation of LIST expands X for each element in the list.

Example

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.

  1. define LIST_OF_VARIABLES \\
        X(value1) \\    X(value2) \\    X(value3)

Then we execute this list to generate the variable declarations:

  1. define X(name) int name;

LIST_OF_VARIABLES

  1. undef X

In a similar way, we can generate a function that prints the variables and their names:

void print_variables()

{
  1. define X(name) printf("%s = %d\", name, name);

LIST_OF_VARIABLES

  1. undef X

}

When run through the C preprocessor, the following code is generated. Line breaks and indentation 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("%s = %d\", "value1", value1);    printf("%s = %d\", "value2", value2);    printf("%s = %d\", "value3", value3);

}

Further reading

  • Wikibooks on X Macros

References

1. ^Meyers, Randy. The New C: X Macros. Dr.Dobb's 2001.
2. ^Bright, Walter. The X Macro. Dr.Dobb's 2010
3. ^Lucas, Andrew. Reduce C-language coding errors with X macros. Embedded.com 2013.

1 : C (programming language)

随便看

 

开放百科全书收录14589846条英语、德语、日语等多语种百科知识,基本涵盖了大多数领域的百科知识,是一部内容自由、开放的电子版国际百科全书。

 

Copyright © 2023 OENC.NET All Rights Reserved
京ICP备2021023879号 更新时间:2024/11/12 2:07:42