问题
I am writing code for an Arduino. The code starts to get long so I want to use some debugging macros, and to be able to show some debugging information on serial port.
For example, I have some macros to define which serial ports I use:
#define SERIAL_GPS Serial1
#define SERIAL_IRIDIUM Serial2
#define SERIAL_VN100 Serial3
How can I write a macro to show the ports I use for each one? I.e. some macro that would print on a debug serial port:
Port for GPS: Serial1
Port for Iridium: Serial2
Port for VN100: Serial3
I have tried:
#define SHOW_VAR_NAME(x) #x
together with:
SERIAL_DEBUG.println(SHOW_VAR_NAME(SERIAL_GPS));
But this prints on serial:
SERIAL_GPS
instead of:
Serial1
because (I guess) the macro pre-processor does only one scan. Any smart way to get this to work?
Note: I take a simple example here, but there are some debug variables (for example, some variables DEBUG_GPS, DEBUG_IRIDIUM and others) that I would really like to print at board startup: I have quite a few of those debug options for separate components, and printing their status at startup would help keep track of which debuggings are activated or not (even if they are all gathered in a header file, it would not hurt to remember the user about all of them).
回答1:
The # preprocessor operator prevents the expansion of its operand. You need to add a layer of indirection so that expansion can occur:
#define SHOW_VAR_NAME_(x) #x
#define SHOW_VAR_NAME(x) SHOW_VAR_NAME_(x)
This functionality is provided by BOOST_PP_STRINGIZE from Boost.Preprocessor, which I recommend using if you start using the preprocessor heavily.
来源:https://stackoverflow.com/questions/49235277/use-a-macro-to-show-the-stringified-content-of-a-macro