简体   繁体   English

用宏初始化C中的LUT?

[英]Initialize LUT in C with macros?

I need a look-up-table in my program describing the size of different types. 我的程序中需要一个查找表来描述不同类型的大小。 Right now I got it like: 现在我明白了:

typedef struct{
     APP_InterfaceType_t Type;  //This is just an enum
     uint8_t Size;
}APP_InterfacesLUT_t;

APP_InterfacesLUT_t MyLUT[] = {...}

Now problem is, I want to insert the content of the LUT from different .h files (I have my reasons) and it has to be done in the pre-processor. 现在的问题是,我想从不同的.h文件中插入LUT的内容(我有理由),它必须在预处理器中完成。

I got the different types in separate .h files, and when I include one of these .h files in my build, the type (described in the .h file) and size should magically appear in the LUT. 我在单独的.h文件中得到了不同的类型,并且当我在构建中包括这些.h文件之一时,类型(在.h文件中描述)和大小应该神奇地出现在LUT中。

So I am wondering if this is possible by calling some kind of Macro inside the .h files? 所以我想知道是否可以通过在.h文件中调用某种宏来实现?

for example: 例如:

REGISTERTYPE(type, size); 

EDIT: The module where the LUT is defined doesn't know anything about the types. 编辑:定义LUT的模块对类型一无所知。 The idea is that when I want to add a new type to the program, I only have to include a header-file and not edit anything in the rest of the program :) 这个想法是,当我想向程序中添加新类型时,只需要包含一个头文件,而无需在程序的其余部分中编辑任何内容:)

Yes, that's possible, but it will probably require you to use some multiple-inclusion and/or ifdef trickery. 是的,这是可能的,但是可能会要求您使用一些多重包含和/或ifdef技巧。

See also X macros , but it becomes more complicated when you need to generalize it to work across multiple headers. 另请参见X宏 ,但是当您需要将其概括化以跨多个标头工作时,它会变得更加复杂。

You could do conditional compilation if your LUT module knows about other modules. 如果您的LUT模块了解其他模块,则可以进行条件编译。 There are many approaches to this (like X-macros as unwind pointed out), but here's something traditional: 有很多方法可以解决此问题(如unwind指出的X宏),但这是传统的方法:

APP_InterfacesLUT_t MyLUT[] = {
#ifdef MODULE_A
    { TYPE_1, 12 },
    { TYPE_2, 45 },
#endif
#ifdef MODULE_B
    { TYPE_2, 22 },
    { TYPE_3, 77 },
#endif
};

If your LUT module doesn't know about other modules, then there's no way around it and you must do this at runtime. 如果您的LUT模块不了解其他模块,则无法解决它,您必须在运行时执行此操作。

Edit: 编辑:

X-macro solution. X宏解决方案。

LUT.c: LUT.c:

APP_InterfacesLUT_t MyLUT[] = {
    #define X(a, b, c)   { a, b },
    #include "interfaces.x"
    #undef X
};

interfaces.x: interfaces.x:

// Molude A
X( TYPE_1, 12, something else )
X( TYPE_2, 45, something else )
// Molude B
X( TYPE_2, 22, something else )
X( TYPE_3, 77, something else )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM