I'm currently working with the NodeMCU ESP12E and MPU6050 IMU using the Arduino IDE and wanted to create a project that has a .h file that declares the variables and functions. In the .cpp file, I have various function definitions. The main.ino file just calls some of these functions. Please find some excerpts of code from each file and the errors I encountered. The errors say the three functions called in the .ino file are undefined even though they are defined in the .cpp file
Algo.h file:
extern int activity_state; // activity_state=1 for RUN and activity_state=0 for WALK
extern float * speedarray; // Dynamic array for storing speed
extern int speedindex;
extern float * timearray; // Dynamic array for storing time
extern int timeindex;
extern unsigned int localPort;
Algo.cpp:
static void pedometerInit() // Initialising all pedometer algorithm variables
{
int i = 0;
//pedometerAlgo varibles
pedi_window_high = 2000;
pedi_window_low = 200;
pedi_sampling_counter = 0;
pedi_refresh_frequency = 50;
validZone = 1;
jatin_index_1 = 0;
jatin_mag = 0;
pedi_max = 0;
.
.
All the functions work on the variables declared in the header file.
Ped_algo.ino:
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(STASSID, STAPSK); // Setting up WiFi station
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(500);
}
Udp.begin(localPort); // Setting up UDP connection
MPU6050_Init(); // Initial configuration of the MPU6050
pedometerInit();
}
void loop() {
pedometerAlgo();
}
Error messages:
Ped_Algo.ino.cpp.o:(.text.loop+0x0): undefined reference to pedometerAlgo()'
in function
loop':
undefined reference to pedometerInit()'
undefined reference to
MPU6050_Init()'
undefined reference to `pedometerInit()'
Error compiling for board NodeMCU 1.0 (ESP-12E Module).
1 Answer 1
Firstly, static
keeps a function from ever being exported globally:
static void pedometerInit() // Initialising all pedometer algorithm variables
should not be static
.
Secondly, extern
does not define a variable, it merely tells the compiler that "this variable exists somewhere. Find it at link time." - however you're not actually defining those variables anywhere. In addition to the extern
hints in the .h
file you need to have the variables in the .cpp
file for the compiler to be able to find them.
int activity_state; // activity_state=1 for RUN and activity_state=0 for WALK
float * speedarray; // Dynamic array for storing speed
int speedindex;
float * timearray; // Dynamic array for storing time
int timeindex;
unsigned int localPort;
void pedometerInit() // Initialising all pedometer algorithm variables
{
... your code ...
}
static void pedometerInit()
thatstatic
means linker is not allowed to use it outside its own compilation unit Algo.cpp (Algo.o)pedometerAlgo::pedometerAlgo()
implemented.