#include guards in C++

I was having issues with an ESP32 project. I needed an instance of

AsyncWiFiManager wifiManager(&server, &dns);

which was sitting in <wifisetupmanager.h>

I needed this in two files – <setup.h> and <endpoints.h>. Ok no big deal, lets add it ๐Ÿ‘… not so fast!… When I added:

#include <wifisetupmanager.h>

In both files, I received the following error:

src/wifisetupmanager.h:9:29: error: redefinition of ‘AsyncWiFiManager wifiManager’ ๐Ÿคทโ€โ™‚๏ธ

We are including the #include twice… so the compiler sees this as a redefinition of that instance…

What do we need to do here? We simply wrap the definition with this

#ifndef WIFIMANAGER
#define WIFIMANAGER
AsyncWebServer server(80);
DNSServer dns;

AsyncWiFiManager wifiManager(&server, &dns);

#endif

What does this do?

#ifndef – check if WIFIMANAGER is defined – WIFIMANAGER could be anything – think of its just like a flag. Its either there or its not. It holds no values and doesnt correspond with anything.

#define WIFIMANAGER – define this flag – again this could be anything, in my case I made it descriptive of what would be below

#endif – close the if statement

So this means that as the compiler moves through, it checks if WIFIMANAGER is defined. It isn’t…yet, so it defines it.

Then the compiler moves to the next file that includes wifisetupmanager.h

as it moves through wifisetupmanager.h – it hits the #ifndef WIFIMANAGER line again. This time though things are different, ITS DEFINED ๐Ÿ™€ dont worry though, because its defined, we now skip redefining the WIFIMANAGER flag but also all the code that is enclosed within that if statement. And our code compiles! ๐Ÿ˜Ž

Hopefully this has been helpful! If you need a hand, get in contact!


Posted

in

, ,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *