考虑:
typedef struct MS{
uint8_t maxlen;
uint8_t curlen;
char buf[1]; // dummy length
} MS;
MS ms7;
char ms7data[6]; /* make storage space */
MS ms100;
char ms100data[99]; /* make storage space */
int main() {
/* .... */
}
Run Code Online (Sandbox Code Playgroud)
例如,意图是,ms7.buf
不仅可以访问自己的char ,还 可以访问以下6,等同于它已被声明为char buf[7]
.我的代码将MS
正确初始化字段,永远不会访问变量ms7data
.
为此,我需要确保编译器将遵循(全局,静态)变量的顺序.我可以依靠吗?(我知道结构字段有保证).
不,订单无法保证.对象可以移动,优化,等等.
实际上,正确的程序不可能确定静态变量所在的顺序(假设在地址空间上甚至存在定义的排序,这可能不适用于分段体系结构等).
如果要保证按顺序出现多个全局对象,则必须将它们放在a中struct
,例如:
static struct
{
MS ms7;
char ms7data[6]; /* make storage space */
MS ms100;
char ms100data[99];
} globals;
Run Code Online (Sandbox Code Playgroud)
请注意,在这种情况下,struct成员之间可能仍然存在填充,但您可以使用编译器扩展来避免这种情况,或者进行sizeof
检查.