Problems creating LiquidCrystal Object inside a Class

Hello All,

I'm working with an ATMega32U4 breakout board (the MT-DB-U4 made by MattairTech), which uses the Arduino CDC bootloader. I was working on creating a library which internally creates an instance of the LiquidCrystal library object to control an LCD screen. The library worked greeat, except that I had to put an #include for the LiquidCrystal.h library at the top of the code in the main program in order for the library to function. I also had includes for the LiquidCrystal.h library inside my library's .cpp and .h files so I'm not sure why I also need to put it in the user's program. I did create a simplified example to illustrate the problem I'm seeing. In the below snippets of code, I show the code for the user program, the library's .cpp file and .h file:

User Program:

#include "Class.h"
#include <LiquidCrystal.h>  //<-- Program bombs if this is left out

TestClass Class1;
void setup()
{
  Class1.LCD.print("Hello World");
}

void loop()
{
  // Do Nothing 
}

Test Library's Header file

#ifndef Class_H
#define Class_H

#include <Arduino.h>
#include <LiquidCrystal.h>

class TestClass
{
  public:
  
  LiquidCrystal LCD;  // LCD Object
  TestClass();        // Class Constructor prototype
};

#endif

Test Library's .cpp file:

#include "Class.h"

TestClass::TestClass()
  : LCD(18, 19, 20, 21, 22, 23, 24)  // Initialize LCD object
{
  LCD.begin(12, 2);     // Start and clear LCD Screen
  LCD.clear();
}

The code in the above example works fine as-is. But if you comment out the "#include <LiquidCrystal.h>" line at the top of the main program, it gives the following error:

In file included from Class.cpp:1:
Class.h:11: error: 'LiquidCrystal' does not name a type
Class.cpp: In constructor 'TestClass::TestClass()':
Class.cpp:5: error: class 'TestClass' does not have any field named 'LCD'
Class.cpp:15: error: 'LCD' was not declared in this scope

I don't want to make the user have to include the LiquidCrystal library external to the library when I already have it included in the library header. Any idea why it is doing this? I did try putting the include inside the library's .cpp file but that didn't seem to work either.

  • Jason O

Jdo300:
I don't want to make the user have to include the LiquidCrystal library external to the library when I already have it included in the library header.

Well that's just tough. You can't do it. Any library used anywhere in the sketch will need to be included in the ino file. Unfortunate, but that's just the way it is.