简体   繁体   中英

Prefixing function calls with macros

Im running into an issue where I need to be able to modify C function calls via a macro.

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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