I'd like to get a C macro (or several) that could serve two purposes:
- Declare a const variable.
- Add that variable to an array.
I.e , if I have this
typedef struct {
int port;
int pin;
} pin_t;
A macro like this
#define DEFINE_PIN(name, port, num)
should expand to something like this
#define NAME port, num
const pin_t[] = {
{NAME}
};
And each definition should append the new defined variable to the array.
I know that a #define cannot expand to #defines but is just an illustration. What I want to accomplish is, on one hand, to define the pin be used wherever necessary and, on the other hand, have an easy way to traverse all the pins, i.e for configuring the hardware gpios.
gcc,gcc -E <file.c>is a good way to test your macro expansions, since it does only runs the preprocessor step on file<file.c>. Just beware that includes are also expanded, so you might temporary remove them.constarray of pins, with each entry having a string member giving its name, and write a function that, given a string, searches the array and returns the pin with that name. If you enable inlining and call the search function with a string literal, a good compiler like gcc will optimize the whole thing out and reduce it to the appropriate constant. Example.