arduinoarduino-idearduino-c++

Linker error in arduino ide when using struct


struct button {
  static int pin;
  bool pressed;
};

button Kreis1Button[] = {15, false};

void setup() {
  pinMode(Kreis1Button[0].pin, INPUT_PULLUP);

}

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

}

Hello,

i want use a struct in my arduino sketch to manage my button data and state. But when i want to use the vriables in the struct i get an linker error.

/home/USER/.arduino15/packages/esp32/tools/xtensa-esp32-elf-gcc/esp-2021r2-patch5-8.4.0/bin/../lib/gcc/xtensa-esp32-elf/8.4.0/../../../../xtensa-esp32-elf/bin/ld: /home/USER/.var/app/cc.arduino.IDE2/cache/arduino/sketches/****/sketch/sketch_may1a.ino.cpp.o:(.literal._Z5setupv+0x0): undefined reference to `button::pin'
collect2: error: ld returned 1 exit status

exit status 1

Compilation error: exit status 1

I already looked into some other issues but cant find a sufficient answer. But i read it could be an error inside the Arduino ide.


Solution

  • A static member must be initialized before you can use the class:

    struct button {
      static int pin;
      bool pressed;
    };
    int button::pin = 15;
    
    button Kreis1Button[] = {false};
    
    void setup() {
      pinMode(Kreis1Button[0].pin, INPUT_PULLUP);
    
    }
    
    void loop() {
      // put your main code here, to run repeatedly:
    
    }
    

    If you intended for each button to have it's own pin number, then pin can't be static. In a class, static means that there is only one of that variable that is shared by all instances of the class. So this only makes sense if all the buttons have the same pin.