在嵌入式C语言世界中,我们经常将配置详细信息存储在标头中,以便可以为特定任务构建库,从而最大程度地减少开销和编译大小。

一个例子是:

//libnameConf.h
#define LIBNAME_WAVE LIBNAME_A

typedef enum {
  LIBNAME_A,
  LIBNAME_B,
  LIBNAME_C
} libname_wave_t;




//libname.c
double coef_arr_a[100] = {...};
double coef_arr_b[100] = {...};
double coef_arr_c[100] = {...};

if (LIBNAME_WAVE == LIBNAME_A) {
  somestruct.waveCoefs = coef_arr_a;
  //do other coef_arr_a specific stuff
} else if (LIBNAME_WAVE == LIBNAME_B) {...}


对于这种特殊情况,我们使用if语句,表明编译器显然会崩溃,这是一件好事,因为我们只想引用coef_arr_a,这样其他代码就不会编译成二进制文件并占用空间。

不幸的是,这产生了警告

warning: comparison between 'enum <anonymous>' and 'enum <anonymous>' [-Wenum-compare]


有没有更好的方法可以避免此警告?

最佳答案

仅使用宏而不使用变量和枚举的方式。

//libnameConf.h
#define LIBNAME_A
// #define LIBNAME_B // Uncomment this line and both comment the above line while changing libs.


然后,我们使用几个这样的条件编译语句。

//libname.c
double coef_arr_a[100] = {...};
double coef_arr_b[100] = {...};

#ifdef LIBNAME_A
  somestruct.waveCoefs = coef_arr_a;
  //do other coef_arr_a specific stuff
#endif
#ifdef LIBNAME_B
  somestruct.waveCoefs = coef_arr_b;
#endif

07-28 03:03
查看更多