gpt4 book ai didi

c - tcc 中的打包结构

转载 作者:太空宇宙 更新时间:2023-11-03 23:25:17 26 4
gpt4 key购买 nike

我正在尝试在 tcc C 编译器中执行打包结构。代码如下,应该支持__attribute __标签:

#include <stdio.h>
#include <stdint.h>

typedef struct _test_t{
char c;
uint16_t i;
char d;
} __attribute__((__packed__)) test_t;

int main(){
test_t x;
x.c = 0xCC;
x.i = 0xAABB;
x.d = 0xDD;

const char *s = (const char *) & x;

unsigned i;
for(i = 0; i < sizeof(x); i++)
printf("%3u %x\n", i, 0xFF & s[i]);

return 0;
}

它适用于 gcc,但不适用于 tcc。我还尝试了 __attribute __((packed)) 和其他一些测试 - 都没有用。

最佳答案

因为您已经找到了 __attribute__ extension只适用于结构的成员,所以他们每个人都应该单独应用它。这是您的代码,稍作修改,使用 tcc 0.9.26 编译,然后以正确的输出运行:

typedef struct {
char c __attribute__((packed));
unsigned short i __attribute__((packed));
char d __attribute__((packed));
} test_t;

int main(void)
{
test_t x;

printf("%zu\n", sizeof(test_t));

x.c = 0xCC;
x.i = 0xAABB;
x.d = 0xDD;

const char *s = (const char *) &x;

unsigned i;
for (i = 0; i < sizeof(x); i++)
printf("%3u %x\n", i, 0xFF & s[i]);

return 0;
}

结果:

4
0 cc
1 bb
2 aa
3 dd

这里有一个问题。正如您可能已经发现的那样,没有标题。正确编写的代码应该有:

#include <stdio.h>
#include <stdint.h> // then replace unsigned short with uint16_t

但是,对于 header ,__attribute__ 不再有效。我不确定这种情况是否总是会发生,但在我的系统 (CentOS 6) 上确实如此。

我发现解释在内部 sys/cdefs.h header 中,其中包含:

/* GCC has various useful declarations that can be made with the
`__attribute__' syntax. All of the ways we use this do fine if
they are omitted for compilers that don't understand it. */
#if !defined __GNUC__ || __GNUC__ < 2
# define __attribute__(xyz) /* Ignore */
#endif

所以 __attribute__ 类函数宏对于 tcc 来说是“过时的”,因为它没有定义 __GNUC__ 宏。这似乎是 tcc 开发人员和标准库(这里是 glibc)编写者之间的一些不一致。

关于c - tcc 中的打包结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28637879/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com