使用 C 预处理器生成样板代码

Using C preprocessor to generate boilerplate code

目前我正在编写一些应该易于扩展的代码。 要添加新条目,用户必须添加:

  1. 新条目的名称
  2. 新条目的大小

名称仅用于填充枚举,大小需要保留一些space来存储它的值。

坦率地说,我不确定这是否可行,因为我实际上是在询问预处理器是否可以正确 split/separate 符号并将其转换为某种样板代码。

因此,例如,我想添加以下条目:

DECLARE_ENTRY(downlinkCounter, sizeof(uint32_t))
DECLARE_ENTRY(uplinkCounter, sizeof(uint32_t))

或者也许:

#define ENTRIES downlinkCounter, sizeof(uint32_t), uplinkCounter, sizeof(uint32_t)

或者:

#define NAME_ENTRIES downlinkCounter, uplinkCounter,
#define SIZE_ENTRIES sizeof(uint32_t), sizeof(uint32_t)

(最后一个选项不是首选,我更喜欢将名称和尺寸紧密配对)

我希望在头文件中将其扩展为以下内容:

typedef enum {
    downlinkCounter,
    uplinkCounter,
} eEntries_t;

并在源文件中展开为:

typedef struct {
    uint8_t downlinkCounter[sizeof(uint32_t)];
    uint8_t uplinkCounter[sizeof(uint32_t)];
} sEntries_t;

我什至可以用 C 预处理器来做这个吗?还是我必须输入这个?

感谢您的帮助!

编译前最好运行一些C代码生成脚本,这样你的代码更清晰易读。

否则,您可以使用各种宏技巧(所谓的“X 宏”)集中预处理器常量。它们有助于避免代码重复,但会使所有内容变得难以阅读。在这种情况下:

#define ENTRY_LIST(X)                   \
  X(downlinkCounter, sizeof(uint32_t))  \
  X(uplinkCounter,   sizeof(uint32_t))  \

然后可以使用各种宏调用此列表以生成特定代码段:

#define ENTRY_ENUM(name, dummy) name,
typedef enum {
  ENTRY_LIST(ENTRY_ENUM)
} eEntries_t;

#define ENTRY_STRUCT(name, size) uint8_t name[size];
typedef struct {
  ENTRY_LIST(ENTRY_STRUCT)
} sEntries_t;

预处理为:

typedef enum {
  downlinkCounter, 
  uplinkCounter,
} eEntries_t;

typedef struct {
  uint8_t downlinkCounter[sizeof(uint32_t)]; 
  uint8_t uplinkCounter[sizeof(uint32_t)];
} sEntries_t;