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

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

问题描述

我正在为 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_PP_STRINGIZE 来自 Boost.Preprocessor,如果您开始大量使用预处理器,我建议您使用它.

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天全站免登陆