Macro-producing macros in C?

人盡茶涼 提交于 2019-11-28 13:32:37

It's not possible in standard C.

Have you considered using M4 macros? I think they are available on most platforms so that should not be a limitation.

M4 GNU page

It's not possible because the macro is done only once.

This doesn't mean you could not use other macros in your macro but you could not do

#define TEST #define HALLO 33

int x = TEST;

and expect x to be 33 afterwards! What you would get is a syntax error because you tried

int x = #define HALLO 33;

Or maybe the compiler already complains about #define in #define.

As everybody has said, you can't do exactly what you are asking for.

You might be able to do something like that by forcing the C preprocesor to run twice, e.g., with a rule like this in the makefile:

.c.pp:
   $(CPP) $< -o $@

Then give your file the extension of test.pp. The Makefile will run it once to generate the .c file, and then the normal run on the .c file will run it a second time.

Personally, I would rather write an external script in Perl or something to generate the C code for me; it's a bit cleaner than playing games with the C pre-processor. It depends on how much code we are talking about.

As per C99 Section 6.10.3.2:

Each # preprocessing token in the replacement list for a function-like macro shall be followed by a parameter as the next preprocessing token in the replacement list.

So, you could certainly put a #define in a macro if you have a parameter named define but it will never do what you desire. This often bugs me since I have to work in C and as such can't use C++ templates.

Try #define make_macro(name,...) name##_fn(name##_info, __VA_ARGS__).

Use like this:

make_macro(name1)
make_macro(name2,1)

and this would generate

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