在 C 中有条件地包含数据 table 列的最佳方法

Best way to conditionally include data table columns in C

我有很多数据 table 可以实现紧密的功能。但是,如果我想要有条件地编译多个数据 table 项,它会使 table 本身变得一团糟。这是一个例子:

//#define USE_UNITS
//#define USE_RAW

typedef struct
{
  uint8_t alarm_num;
  uint8_t dec;
  boolean sign;
  PGM_P label;
  PGM_P label_suffix;
#ifdef  USE_UNITS
  PGM_P units;
#endif
#ifdef  USE_RAW
  boolean raw;
#endif
  boolean newline;
} TEST_TABLE_TYPE;

const TEST_TABLE_TYPE PROGMEM test_table[NUM_ALARMS] =
{
  {ALARM_VIN_UV_LVL, MEAS_VIN_VCAP_VOUT_DEC, false, label_vin_string, label_uv_string,
#ifdef  USE_UNITS
  units_volts_string,
#endif
#ifdef  USE_RAW
  false,
#endif
    false},
  {ALARM_VIN_OV_LVL, MEAS_VIN_VCAP_VOUT_DEC, false, label_vin_string, label_ov_string,
#ifdef  USE_UNITS
      units_volts_string,
#endif
#ifdef  USE_RAW
      false,
#endif
      false},
  {ALARM_IIN_OC_LVL, MEAS_IIN_ICHG_DEC, true, label_iin_string, label_oc_string,
#ifdef  USE_UNITS
    units_amps_string,
#endif
#ifdef  USE_RAW
    false,
#endif
    true},
  {ALARM_VOUT_UV_LVL, MEAS_VIN_VCAP_VOUT_DEC, false, label_vout_string, label_uv_string,
#ifdef  USE_UNITS
      units_volts_string,
#endif
#ifdef  USE_RAW
      false,
#endif
      false}
};

那也只有3件!我可能最好只包含 USE_UNITS 和 USE_RAW.

的每个可能组合选择的 4 个 table 副本

有没有最好的方法让数据 table 有条件地编译?

您可以使用宏来简化此替代方案:

//#define USE_UNITS
//#define USE_RAW

typedef struct {
    uint8_t alarm_num;
    uint8_t dec;
    boolean sign;
    PGM_P label;
    PGM_P label_suffix;
#ifdef  USE_UNITS
    PGM_P units;
#define X_UNITS(x) x,
#else
#define X_UNITS(x)
#endif
#ifdef  USE_RAW
    boolean raw;
#define X_RAW(x) x,
#else
#define X_RAW(x)
#endif
    boolean newline;
} TEST_TABLE_TYPE;

const TEST_TABLE_TYPE PROGMEM test_table[NUM_ALARMS] = {
  { ALARM_VIN_UV_LVL, MEAS_VIN_VCAP_VOUT_DEC, false, label_vin_string, 
    label_uv_string, X_UNITS(units_volts_string) X_RAW(false) false },
  { ALARM_VIN_OV_LVL, MEAS_VIN_VCAP_VOUT_DEC, false, label_vin_string,
    label_ov_string, X_UNITS(units_volts_string) X_RAW(false) false },
  { ALARM_IIN_OC_LVL, MEAS_IIN_ICHG_DEC, true, label_iin_string, 
    label_oc_string, X_UNITS(units_amps_string) X_RAW(false) true },
  { ALARM_VOUT_UV_LVL, MEAS_VIN_VCAP_VOUT_DEC, false, label_vout_string,
    label_uv_string, X_UNITS(units_volts_string) X_RAW(false) false }
};

但更好的解决方案是始终包含所有字段。它不会消耗太多 space 并使代码 更具可读性。

编写一个程序(不一定要用 C 语言)来输出带有表格的 C 代码。

将该程序的输出包含到您的原始程序中。

#include "output_of_intermediary_program.h" // or maybe .c

您可以将此方法集成到 makefile 和其他构建工具中。