Using struct in included cpp file


#1

Hi,

I am trying to use a struct in an included file, but am receiving the error variable 'My_Struct test_struct2' has initializer but incomplete type

How can I use a struct defined in struct_lib.h in the struct_lib.cpp file?

The code:

// main.cpp
#include <Arduino.h>
#include <struct_lib.h>


struct My_Struct test_struct = { 0 };

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

void loop() {}


// struct_lib.h
#ifndef STRUCT_LIB_H_INCLUDED
#define STRUCT_LIB_H_INCLUDED

struct My_Struct {
  int value;
};

extern struct My_Struct test_struct2;
#endif

// struct_lib.cpp
struct My_Struct test_struct2 = { 0 };

I am compiling for an ESP8266 with the Arduino framework.

I found this issue on the Arduino IDE, is this related?
The test code is also here.

Thank you for helping me out!


#2

You forgot to #include "struct_lib.h" in your struct_lib.cpp. Otherwise you are using an undeclared type. It compiles for me when I do that.


#3

Thank you! I just spent far too long trying to find that.