3

Could I implement this in C?

#define X abc

then X_menu(); will be preprocessed as abc_menu();

In another build if I define X def then X_menu(); will be def_menu();

I'm sure there should be a method, but I could not figure out.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user1932637
  • 183
  • 2
  • 12
  • 1
    If users could do this then internal details of standard libraries would need to be named `__l__i__k__e__t__h__i__s` and also I would want to strangle people. Actually even that wouldn't work ... standard libraries would be impossible to implement safely. – Jonathan Wakely Dec 15 '14 at 20:29
  • The usual convention is not to play such tricks with the preprocessor. Even the (working) answer by Ryan Haining should not be used: The indirection adds a big speedbump for the reader, and the savings in typing is minimal. If you must some kind of automatic tool to shortcut your typing, use editior abbreviations. Learning to touch-type helps as well. – cmaster - reinstate monica Dec 15 '14 at 20:41
  • really don't understand this. – user1932637 Dec 15 '14 at 21:08
  • @user1932637 what I gave you works but is a bad idea to actually use – Ryan Haining Dec 15 '14 at 21:50
  • why do you think it's bad idea? – user1932637 Dec 15 '14 at 23:01
  • http://stackoverflow.com/questions/1253934/c-pre-processor-defining-for-generated-function-names this is better solution. thanks all. – user1932637 Dec 15 '14 at 23:18

1 Answers1

4

No, you wouldn't want this behavior as it would be very unsafe and difficult to deal with replacing every X in every name. However, you could use a macro function to do something similar

#define X(F) abc##F
X(_menu();)

## is macro concatenation, so X(_menu();) will expand to abc_menu();

As Roger points out, the macro will also work with the syntax

X(_menu)();

which you may find easier to read

Community
  • 1
  • 1
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174