Hi
I am trying to write Arduino code with multiple C source files, so that I can separate module functionality across multiple source file.
When I do this and try to call functions from one file to the other I get an error undefined reference to this function
Does anyone know if this is possible or not? and if possible how can be done
Rgrds
Leor
Does anyone know if this is possible or not?
Yes, it is.
Before you try to do this, though, you should be aware that the Arduino sketch is converted to a .cpp file for compilation.
C++ supports function overloading. Perhaps you've noticed that Serial.print() allows you to print integers, bytes, arrays, floats, longs, etc. You can do this because there are multiple Serial.print() methods. How does the compiler keep them straight and choose the correct one?
It uses a process called name mangling. The name of the function in the function table is not print. The actual name depends on the name of the class, the name of the function, and the types of all the arguments.
C does not support function overloading, so it does not use or understand or play well with name mangling.
Once can use the extern "C" directive in front of each function name:
extern "C" void someFunc(someType arg1);
This causes the compiler output to be compatible with C++ calling conventions.
A group of functions can be externalized, without the need for prefacing each one:
extern "C" {
void someFunc();
void another();
}
The "extern "C" {" part can be conditionally evaluated, so both the C and C++ compilers can handle the same header file:
#ifdef __cplusplus
extern "C" {
#endif
// The functions
#ifdef __cplusplus
}
#endif
Of course, you can avoid all this rigamarole by simply naming your file with the .cpp extension.