5

I have a lot of functions to declare 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 there a way I can 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"
};
3
  • No, the preprocessor can't do something like that. Use a script in some other language to generate the DEFINE_FOO lines. Commented Jan 29, 2016 at 22:30
  • Sounds like an XY problem. Why this heap of functions ...? What about the bodies ? Commented Jan 29, 2016 at 22:32
  • I would personally just write a quick C# app to write my file for me. Commented Jan 29, 2016 at 22:32

2 Answers 2

8

You could use the X macro trick:

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

Then in your foo.h file you define X as various macros and invoke 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.

Don't remember where I first saw this, maybe it was here.

Sign up to request clarification or add additional context in comments.

Comments

-2

С/С++ preprocessor cannot open files and the like.

But you can use scripting engines like php or python to generate files you need.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.