简体   繁体   English

预处理器宏问题

[英]Problems with preprocessor macros

I wanted to write a debug log print function for my finite state machine that prints the current state, the time in milliseconds and then my message. 我想为我的有限状态机编写一个调试日志打印功能,该功能可以打印当前状态,时间(以毫秒为单位)以及消息。 However, I get random results. 但是,我得到随机结果。 This is what I did: 这是我所做的:

#define DEBUG_PRINT(tag, format, ...) printf("[%10s] %7d: " format "\n", tag, millis(), ##__VA_ARGS__)

When I run: 当我跑步时:

DEBUG_PRINT("SETUP", "%d %d %d %d", 1, 2, 3, 4);

I expect to get: [ SETUP] 0: 1 2 3 4 我希望得到: [ SETUP] 0: 1 2 3 4
But I get: [ SETUP] 0: 0 1 2 3 但是我得到: [ SETUP] 0: 0 1 2 3

Adding an extra %d will get the "4", but I still get an spurious 0. 添加一个额外的%d将得到“ 4”,但我仍然得到一个虚假的0。

My previous debut log macro: DEBUG_PRINT1("%d %d %d %d", 1, 2, 3, 4); 我之前的首次登场日志宏: DEBUG_PRINT1("%d %d %d %d", 1, 2, 3, 4); prints the expected 1 2 3 4 . 打印预期的1 2 3 4

Can you help me to get rid of that extra 0? 您能帮我摆脱那多余的0吗?

The problem is that the millis() function returns an unsigned long , where as the identifier is a %d integer. 问题在于, millis()函数返回一个unsigned long ,其中标识符为%d整数。

Change it to %7ld and it should work fine. 将其更改为%7ld ,它应该可以正常工作。

I have tested it. 我已经测试过了

edit 1: 编辑1:

I have also tested it on a linux system. 我也在Linux系统上进行了测试。 In the linux system this is not a problem there because the size of a linux int is 4 bytes and long is 8 bytes. 在linux系统中,这不是问题,因为linux int的大小为4个字节,而long为8个字节。

On the Arduino however, the size of an int is 2 bytes and long is 4 bytes. 但是,在Arduino上, int的大小为2个字节, long为4个字节。 This screws up the %d identifier on the Arduino, and extends the unsigned long from millis() to the next %d 这会在Arduino上弄乱%d标识符,并将unsigned longmillis()扩展到下一个%d

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM