1

I'm trying to do a macro substitution, but it doesn't work, here is the code:

#define COMLOG      2
#define __COM_ESPECIAL_print(__a, __comNumber)  COM##__comNumber##_print(__a)
#define COM_LOG_print(__a)      __COM_ESPECIAL_print(__a, COMLOG)

but when I try to call with:

COM_LOG_print("pepe");

It makes a non expected substitution:

undefined reference to COMCOMLOG_print

What I hope to get:

COM2_print

Any ideas?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
togarha
  • 163
  • 3
  • 12
  • 3
    Unrelated to your problem, but don't have names with double leading underscore, [they are reserved in all scopes](http://stackoverflow.com/a/228797/440558). – Some programmer dude Aug 14 '15 at 11:19
  • 1
    Take a look at http://stackoverflow.com/questions/1489932/how-to-concatenate-twice-with-the-c-preprocessor-and-expand-a-macro-as-in-arg as well as http://stackoverflow.com/questions/2202147/is-there-a-way-to-control-macro-expansion-order as well as http://stackoverflow.com/questions/8587965/c-pre-processor-macro-expansion – Richard Chambers Aug 14 '15 at 11:26
  • @JoachimPileborg First I put only on underscore, but testing it I change to two only to test... I forgot to return it to only one – togarha Aug 14 '15 at 11:40
  • @togarha Then you have an underscore followed by an upper-case letter, which is *also* reserved in all scopes. :) – Some programmer dude Aug 14 '15 at 11:41
  • @SouravGhosh is a spelling error, I want to write preprocesor, but my fingers are not so fine (it's friday) – togarha Aug 14 '15 at 11:41
  • @JoachimPileborg ok, I will adjust it, thanks – togarha Aug 14 '15 at 11:42
  • @RichardChambers I read these topics, but I don't find the problem, I made the double substitution to allow the change make in two steps, but it doesn't occur – togarha Aug 14 '15 at 11:43

1 Answers1

3

You need one additional macro to expand __comNumber parameter:

#define __COM_ESPECIAL_print_EXP(__a, __comNumber)  COM##__comNumber##_print(__a)

The reason for that is the ## operator (just like #) does not expand its arguments.

An full example might look like:

#include <stdio.h>

#define COMLOG      2
#define __COM_ESPECIAL_print_EXP(__a, __comNumber)  COM##__comNumber##_print(__a)
#define __COM_ESPECIAL_print(__a, __comNumber)  __COM_ESPECIAL_print_EXP(__a, __comNumber)
#define COM_LOG_print(__a)      __COM_ESPECIAL_print(__a, COMLOG)

void COM2_print(const char *s)
{
    printf("%s\n", s);  
}

int main(void)
{
    COM_LOG_print("pepe");
    return 0;
}

Output:

pepe
Grzegorz Szpetkowski
  • 36,988
  • 6
  • 90
  • 137
  • Ok, I need one more step, I think that it is enough with 2 substitution, but it needs 3, thanks a lot – togarha Aug 14 '15 at 11:47