问题
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 #define
s 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.
回答1:
Below is the header file containing the defines so that they can be used in other compilation units:
#include <stdio.h>
#ifndef header_constant
#define header_constant
typedef struct {
int port;
int pin;
} pin_t;
pin_t pinArray[100];
#define DEFINE_PIN(name, port, num,arrayPos) \
const pin_t name = {port, num};\
pinArray[arrayPos]= name;
#endif
Note: the \
character tells the compiler to continue using the next line as part of the macro.
Below is the main program:
# include "headername.h"
void main(){
DEFINE_PIN(pin1,1,2,0);
DEFINE_PIN(pin2,3,4,1);
DEFINE_PIN(pin3,6,5,2);
printf("%d",pin2.pin);
}
来源:https://stackoverflow.com/questions/60975254/declare-a-variable-and-add-it-to-an-array-at-compile-time