Search code examples
c++arduinoesp8266include-guardsplatformio

Class does not name a type with header guard


Due to error, I needed to implement a header guard in my Header file and Cpp since I have never used it before I don't know what went wrong because on some classes it works and on one it just won't... Originally the problem was bigger, but I think I narrowed it down to the origin of the problem.

LedHandler.h

#ifdef LED_HANDLER_H
#define LED_HANDLER_H

#include <Arduino.h>
#include <Adafruit_NeoPixel.h>
#include <FastLED.h>

/* #include "Led/LedFunction.h"
#include "Led/LedStates.h"
#include "Led/Fading.h" */

class LedHandler {
  public:
    LedHandler(int length, uint16_t pin);
    void clear();
    void show();
    void setColor(int s, int r, int g, int b);

    Adafruit_NeoPixel getStrip();
    int getLength();
  private:
    /* LedStates &currentState;
    LedStates &targetState;
    Fader<LedStates> &ledFader; */

    int length;
    Adafruit_NeoPixel strip;
    CRGB* leds;
};

#endif

LedHandler.cpp

#ifdef LED_HANDLER_H
#define LED_HANDLER_H

#include <Adafruit_NeoPixel.h>
#include <FastLED.h

#include "Handlers/LedHandler.h"


LedHandler::LedHandler(int length, uint16_t pin) {
...
}
...
#endif

main.cpp

#define FASTLED_ESP8266_NODEMCU_PIN_ORDER

#include <Arduino.h>
#include <Scheduler.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

#include "Tasks/WifiTask.h"
//#include "Tasks/Networking/UDPTask.h"

//#include "Handlers/GsonHandler.h"
#include "Handlers/LedHandler.h"

LedHandler ledHandler(60, D6);

Error

src\main.cpp:14:1: error: 'LedHandler' does not name a type
 LedHandler ledHandler(60, D6);
 ^
*** [.pio\build\nodemcuv2\src\main.cpp.o] Error 1

Solution

  • As noted by walnut in comments, first issue is that #ifdef should be #ifndef. Now this directive can never be evaluated to true (because this macro is not defined anywhere).

    Also, you shouldn't ever put include guards in your cpp file. As the name suggests, you use them to protect files that included in other files, and cpp files should never be included anywhere.

    Now, with include guard in your cpp file, the following happens:

    1. Code is read from top to bottom
    2. ifndef is encountered, it is true (LED_HANDLER_H is not yet defined)
    3. LED_HANDLER_H is defined
    4. Other headers are included
    5. "Handlers/LedHandler.h" is included
      Now, it's important what #include directive does. It's a simple copy-and-paste of the file content into another file.
    6. #ifdef LED_HANDLER_H from inside LedHandler.h is checked, and it's false (this macro is already defined in step 3)
    7. The whole content of LedHandler.h is skipped due to include guard.