You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在X宏中实现值累加?附可修改的NUMERIC_FIELD_LIST宏定义

Implementing Value Accumulation with Your X Macro Setup

Got it, let's break down how to add value accumulation functionality using your existing NUMERIC_FIELD_LIST X macro. There are two common use cases here—per-field delta accumulation (adding a value to a specific field) and summing all field values together—and I'll cover both below.

1. Per-Field Delta Accumulation (Add a Value to a Specific Field)

You can extend your FIELD macro to automatically generate an accumulation function for each field alongside the existing getter/setter. Here's how to do it:

// Define the FIELD macro to generate getter, setter, AND accumulation functions
#define FIELD(name, type, addr, getter, setter) \
type getter(void) { \
    return *(type*)addr; /* Read from the field's address */ \
} \
void setter(type val) { \
    *(type*)addr = val; /* Write a new value to the field */ \
} \
void add##name(type delta) { \
    *(type*)addr += delta; /* Accumulate delta to the field's current value */ \
}

// Expand your field list to generate all functions
NUMERIC_FIELD_LIST

// Undefine FIELD to prevent conflicts with other macros later
#undef FIELD

What this does:

  • For each field in NUMERIC_FIELD_LIST, this generates an add[FieldName] function (e.g., addTemperatureCalibrationFactor(float delta) or addHumidityCalibrationFactor(float delta)).
  • The accumulation function reads the current value from the field's address, adds the delta, and writes the result back—perfect for incremental adjustments like calibration tweaks.

2. Sum All Numeric Field Values Together

If you need to calculate the total sum of all fields in your list, you can use a one-time X macro expansion to iterate through every field and accumulate their values:

float calculateTotalOfAllFields(void) {
    float total = 0.0f;
    
    // Define a temporary FIELD macro that adds each field's value to the total
    #define FIELD(name, type, addr, getter, setter) \
        total += getter();
    
    // Expand the list to sum all values
    NUMERIC_FIELD_LIST
    
    // Clean up the temporary macro
    #undef FIELD
    
    return total;
}

Key Notes:

  • Type Consistency: This example assumes all fields are float (which matches your list). If you mix types later, you'll need to add type checks or handle type-specific accumulation.
  • Memory Safety: Ensure addr points to valid memory (RAM or mapped EEPROM)—the getter/setter/accumulation functions directly dereference this address.
  • Macro Cleanup: Always #undef FIELD after expansion to avoid unintended conflicts with other code that might use a FIELD macro.

内容的提问来源于stack exchange,提问作者Watusimoto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:52:54