How to globally #define a preprocessor variable?

喜欢而已 提交于 2019-12-08 07:53:12

问题


I'm programming an Arduino sketch in C++. I want the user to be able to #definea constant directly in the sketch.ino file which will be needed to compile the code. The Arduino IDE uses a g++ compiler.

Let's assume we have three files:

sketch.ino
sketch.h
sketch.cpp

In sketch.h I defined

#define OPTION_1 0
#define OPTION_2 1
#define OPTION_3 2
#define OPTION_4 3
#define SLOW 0
#define FAST 1

In sketch.ino the user then defines MYOPTION:

#define MYOPTION OPTION_2

In sketch.h I use the variable to define macros:

#if MYOPTION == OPTION_1 | MYOPTION == OPTION_2
    #define SPEED FAST
#else
    #define SPEED SLOW
#endif

In sketch.cpp I use it to improve time critical code:

MyClass::foo() {
    // do something
    #if SPEED == FAST
    // do more
    #if MYOPTION == OPTION_2
    // do something extra
    #endif
    #endif
    #if MYOPTION == OPTION_4
    // do something else
    #endif
    }

Unfortunately the definition of MYOPTION doesn't seem to be recognized inside sketch.cpp. Hower sketch.cpp does recognize variables defined in sketch.h. Is there a way to define preprocessor variables globally, so they can be accessed in any file that uses them?


回答1:


  • Move the option definitions to a separate file, e.g. options.h. You could also define them in sketch.ino if you like.
  • Include options.h in sketch.ino and sketch.h.
  • Move all the code that relies on the MYOPTION macro from sketch.cpp to sketch.h.
  • Define MYOPTION in sketch.ino before including sketch.h:
#include "options.h"
#define MYOPTION OPTION_2
#include "sketch.h"

Here's an example of a popular library that uses this technique:

https://github.com/PaulStoffregen/Encoder

It allows the user to configure the use of interrupts from the sketch via the ENCODER_DO_NOT_USE_INTERRUPTS and ENCODER_OPTIMIZE_INTERRUPTS macros.



来源:https://stackoverflow.com/questions/45393975/how-to-globally-define-a-preprocessor-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!