Using the C preprocessor to generate function declarations

折月煮酒 提交于 2019-12-05 16:48:04

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.

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

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

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