1

Given the following code:

#define MY_STRINGIFY_MACRO(...) #__VA_ARGS__ #define PORT_MAC(portNum) port: portNum #define LOG_MACRO(...) printf( MY_STRINGIFY_MACRO(__VA_ARGS__) ) 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 ... "*/ } 

When func() is called with a port number, for example 2, the output is:

 port: portNum 

instead of

 port: 2 

And if I use the macro the following way:

 LOG_MACRO( PORT_MAC(2) ); 

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 portNum value?

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Your only option is to replace in the text at runtime can you explain?
You have a const char * (that you're passing to printf). You need to replace the value "manually" (don't forget to duplicate the string before. Modifying a const char* will probably result in a segfault). Another way would be to call LOG_MACRO(PORT_MAC(%d), portNum). But that'd mean LOG_MACRO isn't allowed to use __VA_ARGS__ (because you need to pass __VA_ARGS__ to printf)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.