I've just got started with Arduino and the editor. I'm fairly expericiend in C but new to Ardunio and the IDE. I'm using the online editor.
I keep getting an undefined reference Error for code that should compile/verify.
As an example - I've created a copy of the blink example (whihc works fine) and have started modifying it. I want seperate source files for various functions. My test project has 3 files:
My_Blink.ino
MyDelay.c
MyDelay.h
The Source code of which is fairly simple: My_Blink.ino
I can't see any reason why someone would post this question in a section of the forum that is clearly marked "For problems with Arduino itself, NOT your project".
AWOL:
I can't see any reason why someone would post this question in a section of the forum that is clearly marked "For problems with Arduino itself, NOT your project".
Thread moved.
I put in that section of the forum specifically becuase it seems like a Problem with Ardunio itself - rather than a specific project (hence why I just used a generic project in my example).
However, if it was in the wrong place, I apologise.
MyDelay.h contains the declaration of the do_a_delay function. You must add an #include directive to My_Blink.ino for that file.
But this doesn't solve the error. Why not? You need to understand that Arduino sketches are compiled as C++. When you name your file MyDelay.c, that causes it to be compiled as C. If you want to use C functions in C++ code, the declaration must be wrapped in extern "C" {}. You can do that from the sketch like this:
It will now compile, but notice there is a warning:
MyDelay.c:5:3: warning: implicit declaration of function 'delay'; did you mean 'do_a_delay'? [-Wimplicit-function-declaration]
delay(length);
^~~~~
The declaration of the Arduino delay function is in the Arduino core library. You can bring in that declaration by adding this #include directive:
#include <Arduino.h>
You don't need to do that with .ino files because the Arduino IDE automatically adds the #include directive for Arduino.h to .ino files. However, the Arduino IDE does not mess around with files with other extensions in the sketch (e.g. .h, .c) so you need to do that work yourself when you need to use things from the Arduino core library in those files.
The alternative to extern "C" is to rename MyDelay.c as MyDelay.cpp, which will cause it to be compiled as C++ just like the .ino file.