Declare a variable and add it to an array at compile time

别说谁变了你拦得住时间么 提交于 2021-01-28 03:21:31

问题


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.


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!