Open rasmus25 opened 11 years ago
I agree. I was trying to write my wrapper around MPU6050 and use the DMP. Functions definitions in the header cause linking problems.
There is a trade-off: having function definition in the header file means that unused functions can be optimized away by the compiler, which reduces binary size and is thus really useful on microcontrollers.
The proper solution would be to have function definitions in the .cpp, tell the compiler to put functions in separate sections and tell the linker to discard unreferenced sections, like this SO answer explains.
Another reason for having function definitions in the header files is that it makes it is possible to easily use the preprocessor directives.
Now we can simply do:
#define DEBUG
#include "MPU6050_6Axis_MotionApps20.h"
in our .ino file and all of the MPU6050_6Axis_MotionApps20 functions will be compiled with debug traces on. If the definitions of MPU6050_6Axis_MotionApps20.h were inside a .cpp file we would have to find and edit MPU6050_6Axis_MotionApps20.h (or MPU6050_6Axis_MotionApps20.cpp) to enable those traces.
But you're are correct, function definitions have no place in a .h file. Method definitions are fine though.
We can also do
#include "MPU6050_6Axis_MotionApps20.cpp"
instead of using the IDE library management.
Header files, such as "MPU6050_6Axis_MotionApps20.h" should not contain function implementations. Implementations should go to a separate .cpp file.
This is important because of the way Arduino compiles the code. If I have a multi-file sketch, then every header that I include in any file has to be additionally included from the main .ino also, otherwise the headers are not found. This leads to multiple includes of the same file and, as it is now, multiple identical implementations of DMP functions, so the code will not compile.
I have not checked if this problem exists in any other driver besides MPU6050.