简体   繁体   English

带宏的函数调用前缀

[英]Prefixing function calls with macros

Im running into an issue where I need to be able to modify C function calls via a macro. 我遇到了一个问题,我需要能够通过宏修改C函数调用。

The basic structure is like this: 基本结构如下:

#define foo bar
foo_1(x);
foo_2(x);
foo_3(x);

What I want is for 我想要的是

bar_1(x);
bar_2(x);
bar_3(x);

to be called, however the string macro does not seem to replace the prefixed part of the calls. 被调用,但是字符串宏似乎并不能代替调用的前缀部分。

Can someone point me in the proper direction? 有人可以指出我正确的方向吗?

Macros only apply to full tokens (thank God - they're bad enough as is). 宏仅适用于完整的令牌(感谢上帝-它们已经足够糟糕了)。 In other words, #define foo bar only affects the identified foo , not the identifier foo_1 , because that's not the same token. 换句话说, foo_1 #define foo bar仅影响标识的foo ,而不影响标识符foo_1 ,因为这不是同一标记。

If you can't modify the calling code, there is no way to achieve what you want. 如果您不能修改调用代码,则无法实现所需的代码。 Use a text editor's search&replace or something like that. 使用文本编辑器的搜索和替换等方法。

If what you really want is a snippet of function calling code that you can adjust to different name prefixes as needed, you can write it like this: 如果您真正想要的是可以根据需要调整为不同名称前缀的函数调用代码片段,则可以这样编写:

foo(1)(x);
foo(2)(x);
foo(3)(x);

and before you include this snippet, you define something like this: 在添加此代码段之前,您需要定义以下内容:

#define foo(i) bar_ ## i

Use string concatenation : 使用字符串串联

➤ cat try.h
#define mymacro(msv) bar_##msv
mymacro(1)(x);
➤ gcc -E try.h
# 1 "try.h"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "try.h"

bar_1(x);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM