【问题标题】:#define is not propagated from main program to class.cpp?#define 没有从主程序传播到 class.cpp?
【发布时间】:2016-08-02 06:19:22
【问题描述】:

如果我从 WotClass.h 中注释掉 #define 行,则会出现编译错误:WotClass.cpp:7: error: 'BFLM_DEFINE' was not declared in this scope

它不应该是范围独立的吗?还是顺序有问题?

WotClass.h

#ifndef WOTCLASS_H
#define WOTCLASS_H

#define BFLM_DEFINE 1 // if commented out then compile fails.

class WotClass{
    public:
        WotClass();
        int foo();
    private:
};

#endif

WotClass.cpp

#include "WotClass.h"

WotClass::WotClass(){}

int WotClass::foo(){
    return BFLM_DEFINE;
}

Test.ino

#define BFLM_DEFINE 1 // This is before including class
#include "WotClass.h"

void setup(){
    Serial.begin(115200);
    Serial.println(BFLM_DEFINE);
    WotClass x;
    Serial.print(x.foo());
}

void loop(){}

【问题讨论】:

  • 从 Test 中删除定义,并将其包含在头文件 WotClass.h 中。 cpp 只包含头部,没有定义,因此失败。

标签: c++ class arduino


【解决方案1】:

考虑编译WtoClass.cpp:

  • 首先,预处理器拉入WotClass.h。由于您注释掉了#define,这意味着WotClass.h 没有定义BFLM_DEFINE

  • 不确定Test.ino是什么,但至少从你的代码来看,它与WotClass.cpp的编译无关。

所以,在编译这个源码时,BFLM_DEFINE 确实是未定义的。它可能是在其他一些源文件中定义的,但这与这个编译单元无关。这正是编译器告诉你的:

WotClass.cpp:7: error: 'BFLM_DEFINE' was not declared in this scope

【讨论】:

  • Test.ino 是 Arduino 的主程序。
  • 啊,明白了——不过,它类似于另一个源文件。不同的编译单元。
【解决方案2】:

WotClass.cpp 编译失败。编译此文件时,编译器只能从 WotClass.h 标头中获取 BFLM_DEFINE 标识符。如果没有在那里定义,则编译失败。

【讨论】:

  • 我被告知首先,编译器根据#includes 将所有文件放入一行文本中,然后从上到下编译。这就是为什么我在主程序中包含WotClass.h 之前尝试使用#define BFLM_DEFINE - 它在经典asp 中以这种方式工作(我更喜欢VBA)。这是否意味着它首先编译类然后通过主程序?这就是为什么在 Test.ino 中将 #define 放在 #include 之前没有任何效果的原因。
  • @Combinatix 编译器通常会独立编译 *.cpp 文件。
猜你喜欢
  • 2013-05-18
  • 2014-07-13
  • 1970-01-01
  • 2018-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-31
相关资源
最近更新 更多