简体   繁体   中英

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.

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.

So I am wondering if this is possible by calling some kind of Macro inside the .h files?

for example:

REGISTERTYPE(type, size); 

EDIT: The module where the LUT is defined doesn't know anything about the types. 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.

See also X macros , but it becomes more complicated when you need to generalize it to work across multiple headers.

You could do conditional compilation if your LUT module knows about other modules. There are many approaches to this (like X-macros as unwind pointed out), but here's something traditional:

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.

Edit:

X-macro solution.

LUT.c:

APP_InterfacesLUT_t MyLUT[] = {
    #define X(a, b, c)   { a, b },
    #include "interfaces.x"
    #undef 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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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