user2162550 user2162550 - 8 months ago 40
C Question

Wrong use of stringification

Given the following code:

#define MY_STRINGIFY_MACRO(...) #__VA_ARGS__

#define PORT_MAC(portNum) port: portNum

#define LOG_MACRO(...)

void func(int portNum)
LOG_MACRO( PORT_MAC(portNum) ); /* In a more general way I would use this macro as LOG_MACRO( PORT_MAC(portNum), PORT_MAC(portNum1) ... ); to get output of " port: 2, port: 3 ... "*/

is called with a port number, for example
, the output is:

port: portNum

instead of

port: 2

And if I use the macro the following way:


Then I get the desired output:

port: 2

How can I fix my code so that it could handle both cases and the output will always contain the

Ven Ven

You seem confused about compile-time vs runtime.

A macro runs at compile time (before anything else is done to your code). That's when the replacement happens. At this point, the only thing CPP (the C Pre Processor) considers is text. It doesn't see anything else (and doesn't even care for it to be valid C code!). Then your code is compiled and you get your binary file (a.out by default).

At this point, no code was executed. No functions were called. Only by the time you launch your program ($ ./a.out) are functions called, and parameters passed. What you want to do is not possible. Your only option is to replace in the text at runtime.