Static variable in class with arduino

I'm wokring with Arduino with some classes and namespaces.
I defined a namespaces with static variable, and I change its value in my class, but in for loop, this variable is 0. Why?

general.h:
'namespace GDateTime
{
static DateTime current_time;
};'

DateTimeManager.h:
'#include <Arduino.h>
#include <Wire.h>
#include "RTClib.h"
#include <TimedAction.h>
#include "general.h"
namespace GDateTime
{
static const byte MIN_DATETIME_REQUEST = 1;
class DateTimeManager
{
public:
enum class RtcStatus
{
Disconnected,
Connecting,
Connected,
Error
};

DateTimeManager(byte _min_datetime_request = MIN_DATETIME_REQUEST);

void cycleCheckDateTime();
RtcStatus getRtcStatus();
private:
DateTime current_time;
RtcStatus startRtc();
unsigned long min_datetime_request = 0;
RtcStatus rtc_status = RtcStatus::Disconnected;
static void setDateTime();
TimedAction dateTimeSetter = TimedAction(min_datetime_request * 60000, setDateTime);;
};
};
#endif
'

DateTimeManager.cpp
'#include "DateTimeManager.h"
namespace GDateTime
{
RTC_DS3231 private_rtc;

DateTimeManager::DateTimeManager(byte _min_datetime_request)
{
min_datetime_request = _min_datetime_request;
dateTimeSetter.setInterval(min_datetime_request * 1000);
dateTimeSetter.reset();
rtc_status = startRtc();
GDateTime::current_time = private_rtc.now();
}
static void DateTimeManager::setDateTime()
{
GDateTime::current_time = private_rtc.now();
Serial.print("Min: ");
Serial.println(GDateTime::current_time.minute());
}
void DateTimeManager::cycleCheckDateTime()
{
dateTimeSetter.check();
}

DateTimeManager::RtcStatus DateTimeManager::startRtc()
{
if(private_rtc.begin())
{
return RtcStatus::Connected;
}
else
{
return RtcStatus::Disconnected;
}
}
DateTimeManager::RtcStatus DateTimeManager::getRtcStatus()
{
return rtc_status;
}
}
'

datetime.ino:
'#include "general.h"
#include "DateTimeManager.h"
GDateTime::DateTimeManager *date_time_manager;
DateTime minut;
void setup ()
{
date_time_manager = new GDateTime::DateTimeManager(1);
Serial.begin(9600);
}
void loop ()
{
delay(2000);
//Serial.print("Arloi status: ");
date_time_manager->cycleCheckDateTime();

Serial.println(GDateTime::current_time.minute());
}'

CONSOLE OUTPUT:
Min: 46
0

Your variable is static. Static linkage results in each translation unit having its own independent variable.

You want to declare the variable with external linkage in your header, and then define it in a .cpp file.
Defining variables in header files is usually a bad idea.

Can You make an example plase?

My scope is to declare a variable to use modify from that class, and read the value from loop

extern int foo;
1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.