ESP32 Include header files

Hi

For a school project, I want to use a header file to store config data. I made a config.h file and placed it in the include folder. To prevent it from loading several times I used wrapper #ifndef.
Now I’m still getting a compiling error: multiple definition of `…’. What am I doing wrong? Is the header file not meant to do this? I would like to use this config in several classes.

Code:

#ifndef CONFIG_H
#define CONFIG_H
/*
Setting for whole project
*/

#include "Arduino.h"

///IR beam
#define IRbeam 18
#define LEDPIN 2
uint32_t detectDelay = 10;
uint32_t downDelay = 10;

///NFC sensor
long cardDetectDelay = 2000;
const int DELAY_BETWEEN_CARDS = 500;

#endif /*CONFIG_H*/

You have to split your code into two files:

  • .h file with macros as well as variable and function declarations
  • .c or .cpp file with variable and function definitions

The terms are a bit confusing. The short story is:

Variable declarations declare that a variable exists but do not allocated any space for it. It looks like so:

extern uint32_t detectDelay;

Variable definitions allocate space for a variable and initialize it. They also declare it. It looks like so:

uint32_t detectDelay = 10;

Function declarations declare that a functions exists and what parameter it has but do not generate any code:

int add_numbers(int a, int b);

Function definitions generate the code for a function. They also declare it:

int add_numbers(int a, int b) {
    return a + b;
}

The problem in your code is that the header files contains declarations. So there is space allocated for the variable multiple times and these allocations are in conflict.

The solution is to split them into two files:

config.h

#ifndef CONFIG_H
#define CONFIG_H

#include "Arduino.h"

#define IRbeam 18
#define LEDPIN 2
extern uint32_t detectDelay;
extern uint32_t downDelay;


extern long cardDetectDelay;
extern const int DELAY_BETWEEN_CARDS;

#endif /*CONFIG_H*/

config.cpp

#include "config.h"

uint32_t detectDelay = 10;
uint32_t downDelay = 10;

long cardDetectDelay = 2000;
const int DELAY_BETWEEN_CARDS = 500;
3 Likes