可能是一个天真的问题 - 我曾经在20年前编程并且自那时起编码不多.我C preprocessor
对此后作品如何萎缩的记忆......
我正在编写一个非常简单的C
程序,我试图声明一些静态全局数组,但是它的大小arrays
将依赖于(以非平凡的方式)MODE
变量.类似下面的简化示例.
两个快速点:我知道我可以arrays
根据任何所需的最大尺寸来确定尺寸MODE
,但我不想这样做,因为(与下面的简化示例不同)有时候这些尺寸中的一小部分会非常大其他人很小.
此外,我想使用静态定义的全局数组 - 而不是在运行时动态分配它们.我希望编译器在编译时具有大小.
//** Simplified example of what I'd like to do **// #define SIZE_LIST_1[5] = {2, 7, 23, 33, 12, 76} // I don't think this is valid syntax #define SIZE_LIST_2[5] = {11, 65, 222, 112, 444} #define MODE 4 #define S1 SIZE_LIST_1[MODE] #define S2 SIZE_LIST_2[MODE] int a[S1], b[S2];
Chris Dodd.. 11
在以简单的方式执行此操作之前,您需要首先定义一堆帮助程序宏:
#define CONCAT(A,B) A ## B #define EXPAND_CONCAT(A,B) CONCAT(A, B) #define ARGN(N, LIST) EXPAND_CONCAT(ARG_, N) LIST #define ARG_0(A0, ...) A0 #define ARG_1(A0, A1, ...) A1 #define ARG_2(A0, A1, A2, ...) A2 #define ARG_3(A0, A1, A2, A3, ...) A3 #define ARG_4(A0, A1, A2, A3, A4, ...) A4 #define ARG_5(A0, A1, A2, A3, A4, A5, ...) A5 #define ARG_6(A0, A1, A2, A3, A4, A5, A6, ...) A6 #define ARG_7(A0, A1, A2, A3, A4, A5, A6, A7, ...) A7 #define ARG_8(A0, A1, A2, A3, A4, A5, A6, A7, A8, ...) A8 #define ARG_9(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, ...) A9 #define ARG_10(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, ...) A10 /* above should be in a pp_helper.h header file or some such */ #define SIZE_LIST_1 ( 2, 7, 23, 33, 12, 76) #define SIZE_LIST_2 (11, 65, 222, 112, 444, 1000) #define S1 ARGN(MODE, SIZE_LIST_1) #define S2 ARGN(MODE, SIZE_LIST_2) #define MODE 4 int a[S1], b[S2];
你可以通过样板代码(boost PP,P99)获得一堆预处理器'库',或者你可以自己动手.主要问题是您需要根据您想要处理的最大数量的参数来定义ARG宏.