如何为Arduino库使用包含保护?

时间:2019-02-15 22:10:48

标签: c++ arduino include

为什么在Example.h中将消息打印两次? #pragma once不应该阻止它吗?

Example.h:

#pragma once
#pragma message "Included"
Example.cpp:
#include "Example.h"

Test.ino:

#include "Example.h"

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

输出:

$ ~/Repositories/arduino-1.8.7/arduino --board arduino:avr:mega:cpu=atmega2560 --verify test/Test.ino`
Picked up JAVA_TOOL_OPTIONS: 
Loading configuration...
Initializing packages...
Preparing boards...
Verifying...
In file included from /home/ToBeReplaced/Test/test/Test.ino:1:0:
/home/ToBeReplaced/Arduino/libraries/example/Example.h:2:17: note: #pragma message: Included
 #pragma message "Included"
                 ^
In file included from /home/ToBeReplaced/Arduino/libraries/example/Example.cpp:1:0:
/home/ToBeReplaced/Arduino/libraries/example/Example.h:2:17: note: #pragma message: Included
 #pragma message "Included"
                 ^
Sketch uses 656 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 8183 bytes for local variables. Maximum is 8192 bytes.

1 个答案:

答案 0 :(得分:0)

包含保护可防止将同一标头多次包含在同一翻译单元/代码文件中。
分别编译的两个文件,每个文件都包含带有消息的标头,在编译时将分别显示该消息。

如果您再次将标头和包含保护的标头再次包含在同一个文件中,那么onyl仍然会对该文件显示一次消息。