本文介绍了如何全局#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的定义. Hower 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?

推荐答案

  • 将选项定义移动到单独的文件,例如options.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预处理程序变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 06:16