Hi all,
Now that I have my project working rather well, I decided to improve the structure of the code and organize the code into separate source files to facilitate better reuse of the code in other projects. I am struggling with how to declare and define the variables and functions, and seek some guidance.
Here is what I would like to have:
- My main project sketch that contains the setup() and loop() functions and whatever #include statements I need. Lets call this file: Sketch.ino
- An accompanying file that is only used with Sketch.ino that holds configuration parameters for my sketch such as the network SSID and password, etc. Lets call this Sketch.h
- A file of functions that I will call from Sketch.ini and other projects - lets call this mylib.cpp
- An accompanying file that mylib.cpp as needed, such as mylib.h
(The file extensions need not be what I list above.)
I have, for example, a struct that mylib defines and an object of that type, that I want to assign values to in Sketch.h
I would like mylib files to not reference Sketch.* so that they are portable and could be used in somothersketch.ino
Example structure that I am aiming for:
Sketch.ino
#include "ESP8266WiFi.h"
#include "mylib.h"
#include "mylib.cpp" // ??
#include "Sketch.h"
void setup() {
WiFi.begin(ssid, password); // defined in sketch.h
}
void loop{
int i = 1;
dostuff(i); // defined in mylib
}
Then sketch.h
#include mylib.cpp //?
#include mylib.h //?
// project specific data
const char* ssid = "xxx";
const char* password = "xxx";
myvar[] = {{ .type='M', .pin=4}, { .type='X', .pin=5}}; //struct defined in mylib.h, myvar declared in ?
Then mylib.h
struct mystruct {
char type;
int pin;
}
Then mylib.cpp
#include "mylib.h"
extern mystruct myvar[];
void dostuff(int thing); {
Serial.println(myvar[thing].type);
}
I have tried using extern, various includes, etc but I just have not managed to get the right permutation.
In my code I am getting a link error: undefined reference and I don't even have the structure I am aiming for above yet!
I have tried reading up on the subject but I just get more confused. Can anyone point me to a working simple example of what I am trying to do?