Home > database >  How can I use a macro inside another macro in order to concat the definition of the macro to somethi
How can I use a macro inside another macro in order to concat the definition of the macro to somethi

Time:04-06

I am trying to make a macro that will be take a predefined prefix and concatenate it to the wanted function name in the argument of the macro, but I have been unsuccessful.

For example, while this is the wanted function signature:

void somePrefix__someFunc(int a)

However, when I run it and check the symbol table of the program I end up with the expansion of:

FUNC_PREFIXsomeFunc

What am I doing wrong and how can I do this correctly?

The code I was trying to run:

#include <iostream>
#define CONCAT(A, B) A##B
#define FUNC_PREFIX somePrefix__
#define FUNC_NAME(_func) CONCAT(FUNC_PREFIX, _func)

void FUNC_NAME(someFunc)(int a)
{
    std::cout << a << std::endl;
}

int main()
{
    FUNC_NAME(someFunc)(2);
    return 0;
}

P.S: I tried using the macro without a CONCAT wrapper (directly trying to concat FUNC_PREFIX##_func), but it still did not work.

CodePudding user response:

The ## is always applied before the macro "replacement list" is (re)scanned, so in case CONCAT is expanded before the other items, we won't get the desired result. Whenever we end up with a ## in the replacement list during macro replacement, it is then applied before any further replacement.

So you need an additional helper macro to expand the FUNC_PREFIX, so that it is expanded before CONCAT is:

#include <stdio.h>
#define CONCAT(A, B) A##B
#define CONCAT_EXPAND(A, B) CONCAT(A,B)
#define FUNC_PREFIX somePrefix_
#define FUNC_NAME(func) CONCAT_EXPAND(FUNC_PREFIX, func)

void FUNC_NAME(someFunc)(int a)
{
    printf("%s: %d\n",__func__, a);
}

int main()
{
    FUNC_NAME(someFunc)(2);
    return 0;
}

Output:

somePrefix_someFunc: 2
  • Related