0

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 Sep 16 at 2:03
0

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 in gyro.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.

| improve this answer | |
  • 1
    this 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. – Juraj Apr 18 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 Apr 18 at 12:45
  • 1
    yes. 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 settings – Juraj Apr 18 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 Apr 18 at 14:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.