声明一个变量,并在编译时将其添加到数组中 [英] Declare a variable and add it to an array at compile time
问题描述
我想获得一个(或几个)C宏,它可以用于两个目的:
I'd like to get a C macro (or several) that could serve two purposes:
- 声明一个const变量.
- 将该变量添加到数组中.
即,如果我有这个
typedef struct {
int port;
int pin;
} pin_t;
这样的宏
#define DEFINE_PIN(name, port, num)
应扩展为类似的内容
#define NAME port, num
const pin_t[] = {
{NAME}
};
每个定义都应将新定义的变量附加到数组中.
我知道 #define
不能扩展到 #define
,而只是一个例子.我要完成的任务是,一方面定义要在必要时使用的引脚,另一方面要有一种遍历所有引脚的简单方法,即用于配置硬件gpios.
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.
推荐答案
下面是包含定义的头文件,以便可以在其他编译单元中使用它们:
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.
下面是主程序:
# 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);
}
这篇关于声明一个变量,并在编译时将其添加到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!