Using the C preprocessor to generate function declarations

I have many functions for declaring in this format:

int foo_100(int, int);
int foo_200(int, int);
int foo_300(int, int);
int foo_400(int, int);

typedef int (*foo)(int, int);
struct foo foo_library[] = {
    foo_100,
    foo_200,
    foo_300,
    foo_400
};

Is it possible to use the C preprocessor to partially automate this task? Ideally, something like this:

foo.txt

100
200
300
400

foo.h

typedef int (*foo)(int, int);

#define DEFINE_FOO(id_) int  foo_##id_(int, int);

DEFINE_FOO(#include"foo.txt")

struct foo foo_library[] = {
    #include "foo.txt"
};
+4
source share
2 answers

You can use trick X:

// foo_list.h
#define MY_FUNCTIONS \
  X(foo_100)
  X(foo_200)
  X(foo_300)
  X(foo_400)

Then in your file foo.hyou define Xas various macros and call MY_FUNCTIONS.

// foo.h
#include "foo_list.h"

#define X(NAME) \
int NAME(int, int);

MY_FUNCTIONS

#undef X

#define X(NAME) NAME,

typedef int (*foo)(int, int);
struct foo foo_library[] = {
  MY_FUNCTIONS NULL
};

#undef X

This is often one of the easiest ways to iterate over a list in the C preprocessor.

I don’t remember where I first saw it, maybe it was here .

+6
source
Preprocessor

/C++ ..

, php python, .

-1

Source: https://habr.com/ru/post/1626598/


All Articles