Search code examples
c++arduinoinclude

How can I use an include guard for an Arduino library?


Why is the message printed twice in Example.h? Shouldn't #pragma once prevent it?

Example.h:

#pragma once
#pragma message "Included"

Example.cpp:

#include "Example.h"

Test.ino:

#include "Example.h"

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

Output:

$ ~/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.

Solution

  • Include guards prevent inclusion of the same header more than once into the same translation unit / code file.
    Two files, each being compiled separatly, each including the header with the message, will each show the message when they are compiled.

    If you include the header with the include guard a second time into the same file, then it will nevertheless onyl show the message once for that file.