perencia
perencia

Reputation: 1552

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

I'd like to get a C macro (or several) that could serve two purposes:

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.

Upvotes: 2

Views: 1045

Answers (1)

NoShady420
NoShady420

Reputation: 941

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);
}

Upvotes: 3

Related Questions