【问题标题】:Define variable in a conditional macro gives error在条件宏中定义变量会出错
【发布时间】:2013-10-21 17:38:33
【问题描述】:

我发现了一个在 C 中运行良好但对 Arduino(在 Windows 上)造成问题的问题

#define NO_PROBLEM
#ifdef NO_PROBLEM
  char charBuf[16];
  unsigned int numBuf;
#endif

void setup() {
}
void loop() {
}

这段代码运行良好。但是如果我改变了

#define NO_PROBLEM

//#define NO_PROBLEM

编译器将返回以下错误:

core.a(main.cpp.o):在 main 函数中:C:\Users\user\arduino-1.0.4-windows\arduino-1.0.4\hardware\arduino\cores\arduino/main.cpp :5: 未定义对设置的引用 C:\Users\user\arduino-1.0.4-windows\arduino-1.0.4\hardware\arduino\cores\arduino/main.cpp:15: 未定义对循环的引用

这是一些调试宏的一部分,我希望一些变量只在 DEBUG 模式下存在,所以实际上 NO_PROBLEM 在我的代码中是 DEBUG。

【问题讨论】:

  • 然后将使用这些变量的每一行包装成一个#ifdef...#endif
  • 嗨@H2CO3l。问题不在于我在未定义变量时试图在其他地方使用它。我只是想在一个宏中使用它,在同一个地方定义,就像这样。 #define DEBU`#ifdef DEBUG char charBuf[16]; unsigned int numBuf; #define initDebug() {Serial.begin(115200);} #define debugPrint(message) {Serial.write(message);} #define debugPrintInt(message)\ {\ numBuf = message;\ Serial.write(itoa(numBuf,charBuf, 10));\ } #else #define initDebug() {} #define debugPrint(message) {} #define debugPrintInt(message) {} #endif

标签: c variables arduino c-preprocessor conditional-compilation


【解决方案1】:

这是 IDE 中与原型生成相关的错误。将 IDE 设置更改为详细的编译器输出。如果您查看构建目录并搜索生成的 .cpp 文件,您将看到以下内容:

//#define NO_PROBLEM
#ifdef NO_PROBLEM
  #include "Arduino.h"
void setup();
void loop();
char charBuf[16];
  unsigned int numBuf;
#endif

void setup() {
}
void loop() {
}

对比

#define NO_PROBLEM
#ifdef NO_PROBLEM
  #include "Arduino.h"
void setup();
void loop();
char charBuf[16];
  unsigned int numBuf;
#endif

void setup() {
}
void loop() {
}

这解释了为什么编译器不会使用注释进行编译。

一种解决方法是确保 IDE 可以在宏定义之前获取某些内容,这些内容将被编译器优化掉。例如

namespace trick17 {};
//#define NO_PROBLEM
#ifdef NO_PROBLEM
  char charBuf[16];
  unsigned int numBuf;
#endif

void setup() {
}
void loop() {
}

现在生成的.cpp文件变成了

#include "Arduino.h"
void setup();
void loop();
namespace trick17 {};
//#define NO_PROBLEM
#ifdef NO_PROBLEM
  char charBuf[16];
  unsigned int numBuf;
#endif

void setup() {
}
void loop() {
}

这样编译就OK了。

【讨论】:

  • 感谢您的帮助!这解释了一些事情:)
猜你喜欢
  • 2023-03-12
  • 1970-01-01
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 2021-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多