hojusaram
hojusaram

Reputation: 517

Rename variable in C preprocessor

I have some existing code that uses an enum instead of a function pointer for callbacks. The callback is called using a table: callback_table[enum].

The enums are named with an enum_ prefix and the corresponding function is named with a func_ prefix.

So, function calls involving callbacks look like this:

foo (param, enum_name);

While browsing code I have to take the name part and prefix func_ instead of just doing a "Jump to definition".

I would like to have a macro so that my code looks like this:

foo (param, f2e(func_name));

so that I can keep the existing code unchanged and still be able to do a "Jump to definition".

Is it possible to have such a macro? The simplest solution would be to omit func_ which means that f2e simple attaches the enum_ prefix, but I would prefer a solution where I can still have func_. Is this possible?

Upvotes: 1

Views: 3625

Answers (1)

Lee
Lee

Reputation: 13542

It's a little round-about, but you could do something like this:

(let's assume, for the sake of this example, that you have three possible enum values enum_one, enum_two, and enum_three).

#define enum_func_one enum_one
#define enum_func_two enum_two
#define enum_func_three enum_three

#define f2e(func_name) enum_ ## func_name

the drawback (of course) is that you'll need a special #define for each possible value of your enum.


Alternative

As an alternative, if your only need is to have the function name handy, so you can use your IDE's "jump to definition" feature... you could do something like this:

#define f2e(name, func_name)  enum_ ## name

then your call would look like this:

foo (param, f2e(one, func_one));

a little redundant perhaps, but it would accomplish your goal with minimal intrusion into the rest of your code.

Upvotes: 1

Related Questions