Multiple definition vs Was not declared in this scope

Hi guys,

Is it possible to have one declaration for several files?

I have this time.cpp:

#include <Arduino.h>

#include <DS3231.h>
DS3231 clock(SDA, SCL);

String getTime()
{
  clock.begin();

  String result = String(clock.getDateStr()) + " ";
  result +=  String(clock.getTimeStr());

  return result;
}

void setTime(uint8_t hour, uint8_t min, uint8_t sec, uint8_t date, uint8_t mon, uint16_t year)
{
  clock.begin();

  clock.setTime(hour, min, sec);
  clock.setDate(date, mon, year);
}

It works.

But when I try to divide it into two different getTime.cpp and setTime.cpp with each function by file (first 5 lines of the declaration are in both files) I have the error:

pioenvs/megaatmega2560/src/setTime.cpp.o (symbol from plugin): In function `clock':
(.text+0x0): multiple definition of `clock'

.pioenvs/megaatmega2560/src/getTime.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
*** [.pioenvs/megaatmega2560/firmware.elf] Error 1

I understand the problem but have no idea how to solve this.

This is a pure programming question (which also could have been asked on https://arduino.stackexchange.com/).

There are 3 reference threads with similiar problems (and the same solution):

Short version:

  • Use header files where you declare used / shared objects (tutorial)
  • use extern (tutorial)

In this case you don’t want to duplicate the creation of the clock object. You want to have it created once and have the other files reference the object.

You can create a third file clock.cpp and clock.h which create and declare the clock.

You can also choose to just create it in one file, e.g. in setTime.cpp:

#include <Arduino.h>
#include <DS3231.h>

//Instantiate object here
DS3231 clock(SDA, SCL);

void setTime(uint8_t hour, uint8_t min, uint8_t sec, uint8_t date, uint8_t mon, uint16_t year)
{
  clock.begin();

  clock.setTime(hour, min, sec);
  clock.setDate(date, mon, year);
}

setTime.h

#ifndef SETTIME_H
#define SETTIME_H

#include <Arduino.h>
#include <DS3231.h>

//Declare that somewhere a DS3231 clock object is created by some file.
extern DS3231 clock;

//Available function prototypes
void setTime(uint8_t hour, uint8_t min, uint8_t sec, uint8_t date, uint8_t mon, uint16_t year);

#endif /* SETTIME_H */

getTime.cpp

#include <Arduino.h>
#include "setTime.h" //includes declarations for clock object


String getTime()
{
  clock.begin();

  String result = String(clock.getDateStr()) + " ";
  result +=  String(clock.getTimeStr());

  return result;
}

getTime.h

#ifndef GETTIME_H
#define GETTIME_H

#include <Arduino.h>

String getTime();

#endif /* GETTIME_H */

In general when you only have two functions which are both related to the time, why not just have it in one file, together with the .h header declaring all available functions

1 Like

Thank you, Maximilian, that’s definitely what I want to know about it.