如何通过 C 预处理器 (cpp) 生成列表?
我想做如下的事情:
F_BEGIN
F(f1) {some code}
F(f2) {some code}
...
F(fn) {some code}
F_END
并让它生成以下
int f1() {some code}
int f2() {some code}
...
int fn() {some code}
int (*function_table)(void)[] = { f1, f2, ..., fn };
函数本身很简单。我似乎无法做的是跟踪所有名称,直到 function_table 结束。
I would like to do something like the following:
F_BEGIN
F(f1) {some code}
F(f2) {some code}
...
F(fn) {some code}
F_END
and have it generate the following
int f1() {some code}
int f2() {some code}
...
int fn() {some code}
int (*function_table)(void)[] = { f1, f2, ..., fn };
The functions themselves are easy. What I can't seem to do is to keep track of all of the names until the end for the function_table.
I looked at this question and this question but I couldn't get anything to work for me.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用预处理器执行此操作的正常方法是在一个宏中定义所有函数,该宏将另一个宏作为参数,然后使用其他宏来提取所需的内容。对于你的例子:
The normal way of doing this with the preprocessor is to define all the functions in a macro that takes another macro as an argument, and then use other macros to extract what you want. For your example:
如果您有符合 C99 的编译器,则预处理器具有可变长度参数列表。 P99 有一个预处理器
P99_FOR
可以执行以下操作“代码展开”就像您想要实现的那样。为了接近您的示例,将扩展到以下内容(未经测试)
If you have a C99 complying compiler, the preprocessor has variable length argument lists. P99 has a preprocessor
P99_FOR
that can do "code unrolling" like the one you want to achieve. To stay close to your examplewould expand to the following (untested)
有一个名为 X Macro 的东西,用作:
这就是它的工作原理:
您的问题的解决方案是:
There's this thing called X Macro which is used as:
This is how it works:
Solution for your problem would be:
这是对 CPP 的滥用,但却是一种常见的滥用类型。我处理情况
像这样通过稍后定义虚拟宏
,当您想要使用同一个列表完成不同的操作时
,这有点丑陋和麻烦,但它有效。
This is sort of abuse of CPP but a common type of abuse. I handle situations
like this by defining dummy macros
later, when you want something different done with the same list
It's a bit ugly and cumbersome, but it works.
Boost 是一个 C++ 库,但它的预处理器模块应该仍然适合在 C 中使用。它提供了一些令人惊讶的高级数据类型和功能,供在预处理器中使用。你可以检查一下。
Boost is a C++ library, but it's Preprocessor module should still be good for use in C. It offers some surprisingly advanced data types and functionality for use in the preprocessor. You could check it out.