为配置宏提供默认值

时间:2014-12-13 22:04:20

标签: c macros header-files c-preprocessor

我使用一些宏(#define)作为编译时配置常量。

#define WS_T_1H  700
#define WS_T_1L  150
#define WS_T_0H  150
#define WS_T_0L  700
#define WS_LATCH_NS 6000

这些在我的头文件中。

但是,我希望允许用户在包含它时覆盖它们 - 到目前为止我有这个,但它非常冗长和丑陋。

#ifndef WS_T_1H
#define WS_T_1H  700
#endif

#ifndef WS_T_1L
#define WS_T_1L  150
#endif

#ifndef WS_T_0H
#define WS_T_0H  150
#endif

#ifndef WS_T_0L
#define WS_T_0L  700
#endif

#ifndef WS_LATCH_NS
#define WS_LATCH_NS 6000
#endif

我想知道这是不是正确的方法?这是“最佳做法”吗?

1 个答案:

答案 0 :(得分:0)

这是C的标准习惯用法。如果你不喜欢编写这样的代码(很多人不喜欢),你可以学习autoconf,它提供了一种定义宏默认值的替代语法。然后autoconf将为您编写惯用的C代码。