Splitting cpp files

New to PlatformIO and coming from a Arduino IDE background. I have read a few threads on splitting .ino files into .cpp files and having few issues. I can get the basic examples working but when trying something a little more complex I get stuck.

main.cpp

#include <Arduino.h>
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_PCD8544.h>
#include <screen.h>

Adafruit_PCD8544 display = Adafruit_PCD8544(17, 18, 19, 20, 21);
String version = "v1.0";

void setup()
{
startScreen();
}

void loop()
{
}

screen.cpp

#include <Arduino.h> 
#include "screen.h"

void startScreen()
{
  display.clearDisplay();
  display.println(version);
  display.display();
}

screen.h

void startScreen();

I’m getting the following error:

src/screen.cpp: In function 'void startScreen()':
src/screen.cpp:12:3: error: 'display' was not declared in this scope
   display.clearDisplay();
   ^
src/screen.cpp:14:19: error: 'version' was not declared in this scope
   display.println(version);

What am I missing? Does display and version need to be somehow passed to screen.cpp?

Yes. Since you defined them in another cpp file, the other cpp file doesn’t now anything about it (declaration of them missing). For this external global variable you need to use the extern declaration. add to screen.h:

#include <Arduino.h> // so that String is known
#include <Adafruit_PCD8544.h> //so that Adafruit_PCD8544  is known

//make the global variables from main.cpp visible
extern Adafruit_PCD8544 display;
extern String version;

See references:

2 Likes

Great stuff. Thanks for the example and references.

That makes it a lot clearer

I think it also helps to think of each group of .h and .cpp files as a different country… if you define something in one, it won’t cross the borders until an agreement is made. :wink: In other words, each pair of .h and .cpp files is a walled-garden, and you need to poke holes in those walls to make stuff available between them! :laughing: