0

I have 2 files. Global variables declared in one are not visible in the second.
If I put it all in one file then it works.... but I have 2 files.

I would like the output to be "1.0"

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
/*-------------------------------------------------------*/
class MsgGateway /* redeclared here like a header file */
  {
  public:
    MsgGateway();
    ~MsgGateway();
    void TestFunc(void);
  };
/*-------------------------------------------------------*/
struct settings_t
  {
  char Ver[4]="1.0";
  };
/*-------------------------------------------------------*/
settings_t ESPdata; /* This is the bugger */
MsgGateway* GWClass;
/*-------------------------------------------------------*/
int main(void) /* same as main in cpp */
{
GWClass = new MsgGateway();
GWClass->TestFunc();
return(0);
}
/*-------------------------------------------------------*/

file ScopeTestMore.cpp

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>

struct settings_t
  {
  char Ver[4]="1.0";
  };

class MsgGateway /* initial declaration here in the <header> would usually be */
  {
  public:
    MsgGateway();
    ~MsgGateway();
    void TestFunc(void);
  };

void MsgGateway::TestFunc(void)
{
printf("[%s]",ESPdata.Ver);
}

Compiler output (GCC)

ScopeTestMore.cpp:23:22: error: 'ESPdata' was not declared in this scope
 Serial.printf("[%s]",ESPdata.Ver);
exit status 1
'ESPdata' was not declared in this scope
Dean Smith
  • 27
  • 4

2 Answers2

1

Either extern settings_t ESPdata in the second file, or declare the variable inline and include the header file in both cpps.

Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78
0

In C++ you have declarations and definitions.

You shall make declaration of variable visible in all cpp files (this is usually done by putting declaration in the header included in all cpp files which need to access the global variable).

You shall make definition of variable in exactly one cpp file (there are some exceptions to that rule, but not relevant in this context).

More details e.g. here Variable declaration vs definition. Background of why we need declarations and definitions here: How does the compilation/linking process work?

Slimak
  • 1,396
  • 1
  • 8
  • 17