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