Tutorial for creating multi cpp file arduino project

The way I split code in Platformio is:

create:

  • code.h
  • code.cpp

code.h:

// pragma once prevents the file to be included twice
#pragma once
// #include ...
// all other includes stays here in the .h file

// vars need to be extern
extern String myName;

// prototypes don't need named attributes in the .h file
void sayMyName(String);

code.cpp:

// the only include in the .cpp file
#include "code.h"

String myName = "John";

void sayMyName(String name){

  Serial.print(name);
}

main.cpp

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

void setup(){
  
  sayMyName(myName);
}

void loop(){

}
3 Likes