Home > database >  Pre-processor: Expand a macro only once
Pre-processor: Expand a macro only once

Time:11-23

Is it possible to have a macro expanded only once? In the following example, MYCONCAT is expanded to func_1(10). I want it to expand to func_BAR(10).

#define BAR 1  // included from a file I cannot change
#define FOO BAR

#define MYCONCAT2(c) func_ ## c
#define MYCONCAT(c, x) MYCONCAT2(c)(x)

MYCONCAT(FOO, 10) // is 'func_1(10)', but I want it to be 'func_BAR(10)'

CodePudding user response:

Is it possible to have a macro expanded only once?

No, it is not possible to partially expand a macro.

CodePudding user response:

Include the file that defines BAR only after the last place where MYCONCAT is used (with something that expands to BAR) instead of before it.

CodePudding user response:

Simply change #define BAR to #define _BAR and and remove the _ from func.

#define BAR 1  // included from a file I cannot change
#define FOO _BAR

#define MYCONCAT2(c) func ## c
#define MYCONCAT(c, x) MYCONCAT2(c)(x)

MYCONCAT(FOO, 10) // 'func_BAR(10)'
  • Related