使用宏显示宏的字符串化内容 [英] use a macro to show the stringified content of a macro

查看:107
本文介绍了使用宏显示宏的字符串化内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Arduino写代码.代码开始变得很长,所以我想使用一些调试宏,并能够在串行端口上显示一些调试信息.

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

如何编写宏以显示用于每个端口的端口?IE.一些可以在调试串行端口上打印的宏:

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

我尝试过:

#define SHOW_VAR_NAME(x) #x

与:

SERIAL_DEBUG.println(SHOW_VAR_NAME(SERIAL_GPS));

但这会按顺序打印:

SERIAL_GPS

代替:

Serial1

因为(我猜)宏预处理器仅执行一次扫描.有什么聪明的方法可以使它正常工作吗?

because (I guess) the macro pre-processor does only one scan. Any smart way to get this to work?

注意:我在这里举一个简单的例子,但是有一些调试变量(例如,一些变量DEBUG_GPS,DEBUG_IRIDIUM和其他变量)我很想在板启动时打印:我有很多调试选项对于单独的组件,在启动时打印它们的状态将有助于跟踪哪些调试已激活(即使它们都聚集在头文件中,记住用户的所有知识也不会有任何伤害).

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).

推荐答案

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)

此功能由 提供Boost.Preprocessor中的> BOOST_PP_STRINGIZE ,如果您开始大量使用预处理器,我建议使用.

This functionality is provided by BOOST_PP_STRINGIZE from Boost.Preprocessor, which I recommend using if you start using the preprocessor heavily.

这篇关于使用宏显示宏的字符串化内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆