togarha
togarha

Reputation: 175

C Preprocessor macro substitution

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?

Upvotes: 1

Views: 562

Answers (1)

Grzegorz Szpetkowski
Grzegorz Szpetkowski

Reputation: 37904

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

Upvotes: 3

Related Questions