PlatformIO doesn't compile when header contains global variables

Dear all,

When I’m defining global variables in a .hpp-file, PlatformIO won’t compile correctly. Consider the following example:

Content of main.cpp:

#include <Arduino.h>
#include "test.hpp"

void setup() {
  // put your setup code here, to run once:
}

void loop() {
  // put your main code here, to run repeatedly:
}

Content of test.hpp:

#include "Arduino.h";
uint16_t test_variable;

Content of test.cpp:

#include "test.hpp"

In this case, the result is something like this:

Has somebody experienced this issue and could help me?

Kind regards

You’re misusing global variables here. You must not define your global variable in a header file, only declare its existence. You define it in the CPP file. Because as soon as two different .cpp files include the same header, they will each attempt to create the same global variable, leading to a “multiple definition” error.

This is exactly the mistake you’re having. Instead, restructure the code as such:

test.hpp:

#include <stdint.h>
//declare global var
extern uint16_t test_variable;

test.cpp

#include "test.hpp"
//define global var ONCE
uint16_t test_variable = 0;

main.cpp

#include <Arduino.h>
#include "test.hpp"

void setup() {
    Serial.begin(115200);
    Serial.printf("Global var value: %d\n",  (int) test_variable),
}

void loop() {
  // put your main code here, to run repeatedly:
}
3 Likes

Okay, thanks very much!