Using struct in included cpp file

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!

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.

1 Like

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

Hello all, I’ve got some trouble with this kind of example:
suppose I want to change the value of test_struct2 in struct_lib.cpp (where it is defined) like this :
/ struct_lib.cpp

#include “struct_lib.h”

struct My_Struct test_struct2 = { 0 };

test_struct2.value=3;

It’s does’nt work , when compiling I have the error message :
Compiling .pio/build/uno/src/struct_lib.cpp.o
src/struct_lib.cpp:6:1: error: ‘test_struct2’ does not name a type
test_struct2.value=4;

meanwhile, if I try the same in main.cpp it works !
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println(test_struct.value);
Serial.println(test_struct2.value);
test_struct2.value=3;
}
I’ve been hours on this without success, will appreciate any help, thanks in advance

Are you trying to write into the value field of a global structure without that code being inside any function? That won’t work.

You need to initialize the strucutre not with 0 but with your desired value, like

#include "struct_lib.h"

struct My_Struct test_struct2 = { 
     .value = 3   
 };

That’s exactly what I found 2 minutes ago : it has to be inside a function !!
Many thanks for the confirmation.