【问题标题】:how to override #define in arduino library header如何在arduino库头文件中覆盖#define
【发布时间】:2017-06-28 07:31:50
【问题描述】:

我在一个项目中使用 RunningMedian Arduino 库。

在库头文件中,MEDIAN_MAX_SIZE 预设为 19。

     #define MEDIAN_MAX_SIZE     19  // adjust if needed

我需要在不更改库文件的情况下覆盖标头以使 MEDIAN_MAX_SIZE 为 30,以便将来仍然可以进行更新。

我的倾诉:

     #define RunningMedian::MEDIAN_MAX_SIZE 30     // library over ride ??
     #define ACTIVE_MAX 30 // max active buffer size
     RunningMedian ActiveSamples( ACTIVE_MAX ); // FIFO readings

     This will not compile.

库代码不会创建大于 MEDIAN_MAX_SIZE 的缓冲区。

如何在不更改 RunningMedian.h 文件的情况下覆盖 30 的 19 并仍然更改其类中的 MEDIAN_MAX_SIZE 大小?

【问题讨论】:

  • RunningMedian.h中改一下,如果RunningMedian.cpp单独编译成目标文件就看不到你的重新定义了如果你把它放在别的地方。

标签: c++ class arduino header overriding


【解决方案1】:

您可以#undef MEDIAN_MAX_SIZE 并重新定义它,如下所示:

#ifdef MEDIAN_MAX_SIZE //if the macro MEDIAN_MAX_SIZE is defined 
#undef MEDIAN_MAX_SIZE //un-define it
#define MEDIAN_MAX_SIZE 30//redefine it with the new value
#endif 

您可能希望在完成使用调整后的值后将其重新定义为其原始值,以防万一其他东西依赖于该值是原始值。

【讨论】:

  • @user1213320 或许值得一提的是,这段代码需要出现在第一个定义之后,否则在重新定义之前,旧值可能会在其他地方使用例如RunningMedian.cpp 可能会在包含重新定义的头文件被包含之前单独编译,因此它将使用旧值
【解决方案2】:

Alex Zywicki's answer 非常适合重新定义宏无关紧要的情况。但是,为了安全起见,或者如果您需要确保将宏定义回之前的定义,您可以使用the push_macro and pop_macro pragmas(假设您的编译器支持它):

#ifdef MEDIAN_MAX_SIZE
#pragma push_macro("MEDIAN_MAX_SIZE")
#define MEDIAN_MAX_SIZE 30

// Use the modified value for MEDIAN_MAX_SIZE here

#pragma pop_macro("MEDIAN_MAX_SIZE")

这允许您临时重新定义代码块的宏。

【讨论】:

    【解决方案3】:

    我认为应该可以在您的项目中创建新的头文件(例如 MyRunningMedian.h),只包含您更改的定义:

    #ifndef MEDIAN_MAX_SIZE
    #define MEDIAN_MAX_SIZE     30
    #endif
    

    然后,您需要将此头文件传递给预处理器,以将其作为 RunningMedian 的第一个#include 包含在内。您可以使用 -include 指令来执行此操作,请参阅https://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html

    例如在 PlatformIO 中,您可以在 platformio.ini 中这样做:

    [common]
    build_flags = 
        -include "include/MyRunningMedian.h"
    

    【讨论】:

    • 感谢您提供 platformIO 配置信息!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 2011-09-28
    • 2011-03-02
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多