0

I am trying to use separate files for my PlatformIO Arduino project, but I get this error:

.pio/build/uno/src/test.cpp.o (symbol from plugin): In function `value':
(.text+0x0): multiple definition of `value'
.pio/build/uno/src/main.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2: error: ld returned 1 exit status

To me this error sounds like the one you would get if you don't have include guards or use pragma once, but they didn't solve my problem.

This is my main.cpp:

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

void setup() {
  Serial.begin(115200);
  Serial.println(value);
}

void loop() {
}

test.hpp:

#ifndef TEST_HPP
#define TEST_HPP

int value = 3;

#endif

The test.cpp just includes the test.hpp and does nothing else.

user11914177
  • 885
  • 11
  • 33

1 Answers1

2

You appear to have two source files in your project: main.cpp and test.cpp. Both are probably including test.hpp. So now each source file has independently picked up a value variable. So the linker gets confused because it doesn't know which value each module should use. And you probably do not want multiple instances of this global variable. You just want a single one.

Do this instead in test.hpp:

extern int value;

Then in test.cpp:

int value = 3;
selbie
  • 100,020
  • 15
  • 103
  • 173
  • It has been a while since I last programmed something bigger in pure C++ but I think I never ran into issues there. Is there something different with Arduinos C++? – user11914177 May 22 '21 at 16:55
  • 2
    Nope. This behavior was inherited from C. Hasn't changed for decades. – user4581301 May 22 '21 at 16:56
  • 2
    It's not the C++ compiler having an issue, it's the linker. Some linkers might have command line options be able to just "pick one" if it sees multiple symbol definitions or just give a warning. But in practice, you really do not want to define variables in header files, just declare them. – selbie May 22 '21 at 16:59
  • Thanks for both explanations – user11914177 May 22 '21 at 17:00