C++ #定义未从主程序传播到class.cpp?
如果我从WotClass.h注释掉#define行,我得到编译错误:C++ #定义未从主程序传播到class.cpp?,c++,class,arduino,C++,Class,Arduino,如果我从WotClass.h注释掉#define行,我得到编译错误:WotClass.cpp:7:error:“BFLM#u define”未在此范围内声明 它不应该是范围独立的吗?或者问题是否在顺序中 WotClass.h #ifndef WOTCLASS_H #define WOTCLASS_H #define BFLM_DEFINE 1 // if commented out then compile fails. class WotClass{ public:
WotClass.cpp:7:error:“BFLM#u define”未在此范围内声明
它不应该是范围独立的吗?或者问题是否在顺序中
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(){}
编译
WotClass.cpp
失败。编译此文件时,编译器只能从WotClass.h
头获取BFLM_DEFINE
标识符。如果未在此处定义,则编译失败。考虑编译WtoClass.cpp
:
- 首先,预处理器拉入
。由于您注释掉了WotClass.h
,这意味着#define
没有定义WotClass.h
BFLM\u define
- 不确定什么是
,但至少从您的代码来看,它与Test.ino
的编译没有关系WotClass.cpp
BFLM_DEFINE
实际上是未定义的。它可能是在其他源文件中定义的,但这与编译单元无关。这正是编译器告诉您的:
WotClass.cpp:7: error: 'BFLM_DEFINE' was not declared in this scope
从测试中删除define,并将其包含在标题WotClass.h中。cpp只包含头文件,它没有定义,因此它失败了。Test.ino是Arduino的主程序。啊,明白了,它仍然类似于另一个源文件。不同的编译单元。我被告知,首先,编译器根据
#include
s将所有文件放在一行文本中,然后从上到下编译。这就是为什么我在主程序中包含WotClass.h
之前尝试使用#define BFLM_define
——它在经典asp中是这样工作的(我更喜欢VBA)。这是否意味着它首先编译类,然后通过主程序?这就是为什么在Test.ino中将#define
放在#include
之前没有任何效果的原因。@Combinatix编译器通常独立编译*.cpp文件。