"Multiple definition of 'lcd'" - Issue with C++ for Arduino

I'm using c++ to program an arduino. I am trying to separate each of my main systems into its own c++ and header file. I am using a library for the LCD but I'm having trouble using it. I want to declare it in lcd.h so that I can access it from any other script that wants to print to the LCD.

Upon building, I get this error:

1
2
3
.pioenvs\uno\src\window.cpp.o (symbol from plugin): In function `lcd':
(.text+0x0): multiple definition of `lcd'
.pioenvs\uno\src\lcd.cpp.o (symbol from plugin):(.text+0x0): first defined here


Below are some of my scripts (I have deleted irrelevant sections of the code).

window.cpp:
1
2
3
4
5
6
7
8
9
10
//----LIBRARIES----
#include "window.h"
#include "lcd.h"

//----IMPLEMENTATIONS----
void OpenWindow()
{
    lcd.setCursor(0, 0);
    lcd.print("testing123");
}


lcd.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//----LIBRARIES----
#include "lcd.h"

//----IMPLEMENTATIONS----
void InitializeLCD()
{
    //initialize lcd for 16 columns and 2 rows
    lcd.begin(16, 2);

    //inform user that the system is Initializing
    lcd.setCursor(0, 0);
    lcd.print("Initializing");

    delay(3000);

    lcd.clear();
}


lcd.h:
1
2
3
4
5
6
7
8
9
10
11
12
#ifndef lcd_h
#define lcd_h

//----LIBRARIES----
#include "pins.h"
#include <LiquidCrystalSerial.h>

//----DECLARATIONS----
LiquidCrystalSerial lcd(lcdPin);
void InitializeLCD();

#endif //lcd_h 


LiquidCrystalSerial.h (an arduino library):
1
2
3
4
class LiquidCrystalSerial : public Print {
public:
    LiquidCrystalSerial(uint8_t ssPin);   //SPI to ShiftRegister 74HC595
};
Last edited on
You are creating an object named lcd in a header. You are then including that header in two different cpp files, so you have two files with the same object being created in them. You are not allowed to create the same object twice in one program.
Last edited on
What should I be doing? When I try declaring it like this: LiquidCrystalSerial lcd;
it tells me there's no matching function for call to 'LiquidCrystalSerial::LiquidCrystalSerial()
That's the same problem. Trying to create an object named lcd more than once in the same program.

Looks like you're trying to create a global variable. Now you know what it's called, you can google "c++ global variable".

They're generally regarded as a bad idea, but that's what you're trying to do here, so now you can look it up.
Ok I'll give it a try.
I have now solved it. Below are the changed I have made:

lcd.h:
LiquidCrystalSerial lcd(lcdPin) becomes extern LiquidCrystalSerial lcd

lcd.cpp:
Added: extern LiquidCrystalSerial lcd(lcdPin)
Topic archived. No new replies allowed.