如何命名 C 结构中未命名的字段?

问题描述 投票:0回答:2

让我们考虑这个结构:

struct {
    int a;
    int _reserved_000_[2];
    int b;
    int _reserved_001_[12];
    int c;    
};

永远不要读取或写入保留字段。我的结构代表一个描述符,用于寻址 FPGA,其中我有很多

reserved
字段。我最终将它们命名为随机命名,因为多年后最初的升序编号不再具有任何意义。

所以我现在有:

struct {
    int a;
    int _reserved_3hjdds1_[2];
    int b;
    int _reserved_40iuljk_[12];
    int c;    
};

只有空字段会更方便:

struct {
    int a;
    int;
    int b;
    int;
    int c;    
};

但是没用。

还有什么其他选择可以避免为

reserved
字段找到唯一名称?

c structure naming-conventions
2个回答
4
投票

应该可以通过一点宏观魔法来实现你想要的:

#include <stdint.h>

#define CONCAT(x, y) x ## y
#define EXPAND(x, y) CONCAT(x, y)
#define RESERVED EXPAND(reserved, __LINE__)

struct
{
  uint32_t x;
  uint32_t RESERVED;
  uint16_t y;
  uint64_t RESERVED[10];
} s;

这为您提供了诸如

reserved11
reserved13
之类的标识符,但名称显然无关紧要。


0
投票

我知道,这个答案来得太晚了,但是使用未命名的位文件怎么样?

struct {
    int a;
    int : sizeof(int) * 8;
    int b;
    int : sizeof(int) * 8;
    int c;
};

这是 ISO-C89 标准,适用于我目前遇到的所有 C 和 C++ 编译器,包括:gcc、g++、clang、Borland C++,甚至是旧的 TurboC。

© www.soinside.com 2019 - 2024. All rights reserved.