Dave
Dave

Reputation: 15

Access from multiple source files to one struct array

I tried to upgrade my "working code" with a new function. For this I tried to outsource some functionality into separate files.

At the moment I'm not sure what to do and I can't find a solution for the problem. The code below is only a little part of the code, but I hope it is enough to explain what is going wrong.

I need a global struct array as shown below in global_def. I need access to the same data field from different files (functions).

If I do it in this way, I get the following error:

error: invalid use of incomplete type 'struct resultFieldColor
   setFieldColor(fieldNr , resultFieldColorArray[fieldNr].resultHue , resultFieldColorArray[fieldNr].resultSaturation, resultFieldColorArray[fieldNr].reusltBrightness , ledCounter)

global_def.h

#ifndef GLOBAL_DEF_H
#define GLOBAL_DEF_H
        
struct resultFieldColor;
extern resultFieldColor resultFieldColorArray[];

global_def.cpp

struct resultFieldColor
{
    byte resultHue = 0;
    byte resultSaturation = 0;
    byte reusltBrightness = 0;
};

resultFieldColor resultFieldColorArray[5];

colorFuncOne.cpp

#include <GLOBAL_DEF.h>
#include <LED_control.h>

setFieldColor(fieldNr , resultFieldColorArray[fieldNr].resultHue , resultFieldColorArray[fieldNr].resultSaturation, resultFieldColorArray[fieldNr].reusltBrightness , ledCounter);

colorFuncTwo.cpp

#include <GLOBAL_DEF.h>
#include <LED_control.h>

setFieldColor(fieldNr , resultFieldColorArray[fieldNr].resultHue , resultFieldColorArray[fieldNr].resultSaturation, resultFieldColorArray[fieldNr].reusltBrightness , ledCounter);

Upvotes: 0

Views: 123

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70367

The struct's layout has to be included in the header file.

struct ResultFieldColor {
  byte resultHue = 0;
  byte resultSaturation = 0;
  byte resultBrightness = 0;
};

You may have heard people say not to do this. What they meant was that function implementations shouldn't be in the header, so if you have a function foo, the header should look like

void foo(int x);

and the C++ file should have the body, as

void foo(int x) {
  // Look at me, I'm a function ^.^
}

But structs/classes need to have their layout available in the header. That includes any function declarations (though not their definitions), any template functions (definitions and declarations), and any instance variables.

Note that there are some tricks to work around this, but they tend to be complicated and carry runtime implications, so it's best to simply include the variables in the header file generally.

Upvotes: 2

Related Questions