2016-08-02 43 views
0

如果我注释掉WotClass.h中的#define行,我得到了编译错误:WotClass.cpp:7: error: 'BFLM_DEFINE' was not declared in this scope#define不会从主程序传播到class.cpp?

是不是应该是范围独立的?或者是订单中的问题?

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(){} 
+0

从Test中删除define,并将其包含在头文件WotClass.h中。 cpp只包含标题,它没有定义,因此失败。 – RvdK

回答

5

考虑的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 
+0

Test.ino是Arduino的主要程序。 – Combinatix

+0

啊,明白了 - 仍然是类似于另一个源文件。不同的编译单元。 –

2

WotClass.cpp编译失败。在编译该文件时,编译器只能从WotClass.h标头获得BFLM_DEFINE标识符。如果没有定义,编译失败。

+0

编译单元,而不是模块。 – LogicStuff

+0

我被告知,首先,编译器将所有文件放入单行文本中,基于'#include's,然后从上到下进行编译。这就是为什么我在将'WotClass.h'包含在主程序之前尝试使用'#define BFLM_DEFINE'的原因 - 它在经典的asp(我是更多的VBA人)中以这种方式工作。这是否意味着首先编译类,然后通过主程序?那么为什么在Test.ino中'#include'之前放置'#define'没有任何作用。 – Combinatix

+0

@Combinatix编译器通常独立编译* .cpp文件。 – dlask