首页 > 解决方案 > Serial.printf 宏的类型警告

问题描述

我在我的 platform.io 代码中使用这个宏能够集中激活/停用所有串行打印:

// DEBUG_PRINTF 
// Print string / value in new line with millis timestamp, function name + line number and message
// Usage: DEBUG_PRINTF("Printf Parameter: %s - %d \n", stringvar, value);
#define DEBUG_PRINTF(fmt, ...) \
   do                          \
   {                           \
      Serial.printf("%d: %s:%zu - " fmt, millis(), __PRETTY_FUNCTION__, __LINE__, __VA_ARGS__); \
   } while (0)

这工作得很好,除了很多关于错误参数类型的编译器警告:

server\src\wifi.cpp:85:3: note: in expansion of macro 'DEBUG_PRINTF'
   DEBUG_PRINTF("[INFO] Starting WIFI Access Point with SSID: %s\n", AP_SSID);
   ^
server\lib\DebugUtils/DebugUtils.h:54:94: warning: format '%d' expects argument of type 'int', but argument 3 has type 'long unsigned int' [-Wformat=]
       Serial.printf("%d: %s:%zu - " fmt, millis(), __PRETTY_FUNCTION__, __LINE__, __VA_ARGS__); \
                                                                                              ^

对应的代码如下所示:

  // Create WIFI Access Point
  DEBUG_PRINTF("[INFO] Starting WIFI Access Point with SSID: %s\n", AP_SSID);

AP_SSID是一个static const char

警告出现在我当前使用宏的每个地方,无论我传递什么类型的变量。
有没有办法摆脱警告?

标签: arduinoarduino-c++platformio

解决方案


感谢@πάνταῥεῖ 我解决了这个问题:

编译器警告是由于millis()函数返回unsigned long类型。宏现在看起来像这样并且可以正常工作而没有任何警告:

#define DEBUG_PRINTF(fmt, ...)                                                                    \
   do                                                                                             \
   {                                                                                              \
      Serial.printf("%lu: %s:%d - " fmt, millis(), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__); \
   } while (0)

示例用法:

DEBUG_PRINTF("[INFO] Webserver running: http://%d.%d.%d.%d:%d\n", ESP_IP[0], ESP_IP[1], ESP_IP[2], ESP_IP[3], HTTP_PORT);

推荐阅读