Royce
Royce

Reputation: 585

Scope of variables in C++

for the sake of overview, I wanted to outsource a few functions in another file. Therefore I created a corresponding cpp and h file and put the funtions in there:

#include <routines.h>
void splash()
{
    oled.startScreen();
    oled.clear();
    oled.drawImage(start_logo, 0, 0, 128, 8);
}
void prepareDisplay(){

  unsigned int i,k;
  unsigned char ch[5];
  
  oled.clear();
  oled.startScreen();
  
  
  oled.cursorTo(0,0);
  oled.printString( "ATTiny");
}

Problem is that those functions use variables (oled, start_logo) from the main file which leads to them being out of scope. Main.cpp file:

#include <Arduino.h>
#include "SSD1306_minimal.h"
#include <EEPROM.h>
#include <routines.h>


//eeprom adresses:
byte calibratedAddress = 0;

//global variables:
bool isCalibrated;

//pin definitions:
const byte led = PA5;

SSD1306_Mini oled;

const unsigned char start_logo [] PROGMEM = {
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ongoing...
};

void setup(){   
  
  oled.init(0x3c);
  oled.clear();

  delay(1000);

  splash();
  delay(8000);
  
  oled.clear();      
}    

void loop() {
}

Is it somehow possible to "hand over" the variables to the outsourced functions and if yes, how?

Thanks in advance for your help!

Upvotes: 0

Views: 206

Answers (1)

AnthoFoxo
AnthoFoxo

Reputation: 191

There's many ways to approach this. One easy way is to pass the needed varaible as an argument into the functions that need it.

// Pass the values needed as arguments
void splash(byte oled, unsigned char* start_logo)
{
    oled.startScreen();
    oled.clear();
    oled.drawImage(start_logo, 0, 0, 128, 8);
}

Another way is to keep the functions as is and declare the variables in the new cpp file

// extern says that this variable is not defined .cpp file
// It's defined in another file
extern SSD1306_Mini oled;

// static in this context makes this variable only visible to this .cpp file
// extern in another file can't get this
static const unsigned char start_logo[] = {
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // more
};

void splash()
{
    oled.startScreen();
    oled.clear();
    oled.drawImage(start_logo, 0, 0, 128, 8);
}
void prepareDisplay(){

  unsigned int i,k;
  unsigned char ch[5];
  
  oled.clear();
  oled.startScreen();
  
  
  oled.cursorTo(0,0);
  oled.printString( "ATTiny");
}

Upvotes: 1

Related Questions