如何全局#define 预处理器变量? [英] How to globally #define a preprocessor variable?

查看:33
本文介绍了如何全局#define 预处理器变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 C++ 编写 Arduino 草图.我希望用户能够直接在sketch.ino 文件中#define一个常量,这将需要编译代码.Arduino IDE 使用 g++ 编译器.

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.

假设我们有三个文件:

sketch.ino
sketch.h
sketch.cpp

在sketch.h中我定义了

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

在sketch.ino中,用户定义MYOPTION:

In sketch.ino the user then defines MYOPTION:

#define MYOPTION OPTION_2

在 Sketch.h 中,我使用变量来定义宏:

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

在 Sketch.cpp 中,我用它来改进时间关键代码:

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
    }

不幸的是,在 Sketch.cpp 中似乎无法识别 MYOPTION 的定义.然而,sketch.cpp 确实识别了sketch.h 中定义的变量.有没有办法全局定义预处理器变量,以便可以在使用它们的任何文件中访问它们?

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?

推荐答案

  • 将选项定义移动到单独的文件中,例如选项.h.如果您愿意,也可以在 Sketch.ino 中定义它们.
  • 在sketch.ino 和sketch.h 中包含options.h.
  • 将所有依赖于 MYOPTION 宏的代码从 Sketch.cpp 移动到 Sketch.h.
  • 在包含sketch.h之前在sketch.ino中定义MYOPTION:
    • 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

      它允许用户通过 ENCODER_DO_NOT_USE_INTERRUPTSENCODER_OPTIMIZE_INTERRUPTS 宏从草图中配置中断的使用.

      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.

      这篇关于如何全局#define 预处理器变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆