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

标签 c c-preprocessor

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

//#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个项目!我最好只包括 4 个由 USE_UNITS 和 USE_RAW 的每种可能组合选择的表的副本。

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

最佳答案

您可以使用宏来使此替代方案不那么冗长:

//#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 }
};

但更好的解决方案是始终包含所有字段。它不会占用太多空间并使代码很多可读性更高。

关于c - 在 C 中有条件地包含数据表列的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35677969/

相关文章:

c - 在不知道要输入的字符串大小的情况下动态分配内存

c - 程序运行时出现段错误

c - 宏中的双斜线注​​释替换

c++ - 是否有独立的 C++ 源代码预处理器?

C程序计算通过或失败的分数并在输入负数时退出

c - 如何重复将文本 append 到 C 中的字符串?

printing - 是否有一种可移植的方法来打印来自 C 预处理器的消息?

c - 使用宏构造函数

使用预处理器计算奇偶校验位(通过 ref 调用的奇偶校验功能样式)

c - 在特定 C 程序中使用 '&'