2017-09-13 45 views
0

我已经定义了一个宏,如下所示。将输入存储到数组中的宏(C)

#define NAME_OUT(name_in) PRE_##name_in##_POST 

我想通过使用我已定义在表/数组中的名称来遍历此宏。是否有可能做这样的事情?如果是的话,我会如何做到这一点?

注意:上述例子是仅用于说明目的:)

+3

迭代虽然宏?你什么意思?无论如何,我非常怀疑你可以。宏“名称”仅在预处理阶段之前存在。 –

+0

[boost预处理程序库](http://www.boost.org/doc/libs/1_63_0/libs/preprocessor/doc/index.html)可以使用预处理程序执行某些类型的迭代。它似乎不适合你直接做的事情,但可能你可以改变你使用库的方法。我们确实需要更详细的问题给你提供有用的信息。 – Jonesinator

回答

0

这不是完全清楚你的要求,但它听起来很像你正在寻找的“X宏”的格局:

#include <stdio.h> 

// list of data 
#define NAME_LIST \ 
    X(foo)   \ 
    X(bar)   \ 
    X(hello)  \ 
    X(world) 


// whatever you are actually using these for, maybe an enum or variable names? 
typedef enum 
{ 
    // temporarily define the meaning of "X" for all data in the list: 
    #define X(name) PRE_##name##_POST, 
    NAME_LIST 
    #undef X // always undef when done 
} whatever_t; 


// helper macro to print the name of the enum  
#define STRINGIFY(str) #str 


int main() 
{ 
    #define X(name) printf("%s %d\n", STRINGIFY(PRE_##name##_POST), PRE_##name##_POST); 
    NAME_LIST 
    #undef X 
} 

输出:

PRE_foo_POST 0 
PRE_bar_POST 1 
PRE_hello_POST 2 
PRE_world_POST 3