2016-08-02 19 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