Globals declaration in header

Hello folks,

I wrote a programm with all global declaration in main.cpp, which is working. Now, I want to split this into a .h and .cpp to implement this in an other project. But I need a global declaration in diffrent .h/.cpp files.

Among other things, a struct, I used this example for it and seems to be working. But with a global String not.

I hope someone got a hint or a better structuring for me.

Working with Platiform.io in vscode and an esp32-dev-kit.

main.cpp

#include "DataUtils.h"
#include "defines.h"

struct profil_t profil;
String serialnumber = "";

void setup()
{
  loadfromDatastore();
}

void loop()
{
  /* Code stuff */
}

defines.h

#ifndef DEFINES_H_
#define DEFINES_H_

#include "Arduino.h"

#define N 30 

struct data_t
{
    int x = 0;
    double y = 0.0;
};

struct profil_t
{
    int length = N;
    bool active = false;
    profil_t data[N];
};

String serialnumber;

#endif

DataUtils.h

#ifndef DATAUTILS_H_
#define DATAUTILS_H_

#include <Arduino.h>
#include <ArduinoJson.h>
#include <Preferences.h>
#include "defines.h"

extern profil_t profil;     
extern String serialnumber; 
Preferences datastore;      

void loadfromDatastore();

#endif

DataUtilis.cpp

#include <Arduino.h>
#include "DataUtils.h"

void loadfromDatastore()
{
  /* Loading serialnumber and profil from Preferences */
}

Thanks!
fmvoxa

Put extern String serialnumber; in the header and String serialnumber; in one of the .cpp files, e.g. in main.cpp.

2 Likes

This was it!

I think the best to do, when I write a .cpp to the defines.h or? So I have all my globals in one file?

This is a general C++ question, not really PIO-specific.
I suggest googling for “c++ definition vs declaration”.

You are right. I have a look at his! Thank you!