Sorry if this question been asked. I'm trying to activate certain function in a class using a macro defined in the class from main.cpp. I'm using jrowberg MPU6050 library if that matters.
main.cpp
#include "gyro.h"
gyro gyro(Serial);
#define OUTPUT_READABLE_EULER
void setup(){
...
}
void loop(){
...
}
gyro.cpp
#include "gyro.h"
#ifdef OUTPUT_READABLE_EULER
// display Euler angles in degrees
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetEuler(euler, &q);
serial_.print("euler\t");
serial_.print(euler[0] * 180/M_PI);
serial_.print("\t");
serial_.print(euler[1] * 180/M_PI);
serial_.print("\t");
serial_.println(euler[2] * 180/M_PI);
#endif
If I define OUTPUT_READABLE_EULER
in gyro.h
, it works. But I want to do it from main.cpp.
-
Try putting the define before you include the file.Delta_G– Delta_G2020年09月16日 02:03:56 +00:00Commented Sep 16, 2020 at 2:03
1 Answer 1
You cannot not, but also you should not try to define a macro in a cpp file and use it in another cpp file.
Instead, you have to define it in a h (header) file, which is included in both cpp files.
Why would you define it in main.cpp
or main.h
anyway if you don't use it in those files?
You have mainly three options:
- Define it in
gyro.h
so you include it ingyro.cpp
where you use it. You can later use it in other files as well. - Define it in
gyro.cpp
so you can use it only in that file. This prevents the macro being used in other files (which can be safer). - Define it in a separate file, e.g.
euler.h
and include this header file everywhere you need it.
See also Juraj's comments below.
-
1this applies if the define should by in a source file. this kind of defines is usually set on compiler command line as -D. the Arduino IDE doesn't have -D define configuration for a project.2020年04月18日 12:40:13 +00:00Commented Apr 18, 2020 at 12:40
-
@Juraj in that case it could be an option to create a specific header file with those macros (one in this case) and include them in every file.Michel Keijzers– Michel Keijzers2020年04月18日 12:45:15 +00:00Commented Apr 18, 2020 at 12:45
-
1yes. it is the way if the macro should be used only in the sketch's files (project). inconvenient is it for libraries. then the user must go to library folder and a modifiy a file there, but then it applies for all projects. if the setting is boards specific or one has a customized board definition for a project, then -D can be set in boards.local.txt as build.extra_flags. for example in Eclipse -D can be set in project's settings2020年04月18日 12:51:29 +00:00Commented Apr 18, 2020 at 12:51
-
@Juraj Thanks for that additional info. However, that doesn't work in the IDE I guess ?(as the Arduino IDE is not eclipse based)Michel Keijzers– Michel Keijzers2020年04月18日 14:25:00 +00:00Commented Apr 18, 2020 at 14:25