我正在尝试在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 %xn", i, 0xFF & s[i]);
return 0;
}
它在gcc中工作,但在tcc上不工作。我还尝试了__attribute __((packed))和其他一些测试,但都不起作用。
正如您已经发现的,__attribute__
扩展只适用于结构的成员,因此每个成员都应该单独应用它。这是您的代码,经过了一些小的修改,使用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("%zun", 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 %xn", 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
但是,有了标头,__attribute__
就不再工作了。我不确定这种情况是否总是发生,但在我的系统(Centos6)上,它确实是这样做的。
正如我发现的那样,解释在于内部sys/cdefs.h
标头,其中包含:
/* 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
)编写人员之间似乎有些不一致。
我可以确认,至少在tcc 0.9.26属性((packed))上结构成员不起作用。使用Windows风格的打包杂注效果很好:
#if defined(__TINYC__)
#pragma pack(1)
#endif
typedef struct {
uint16_t ..
} interrupt_gate_descriptor_t;
#if defined(__TINYC__)
#pragma pack(1)
#endif
TCC似乎有错误。
根据包括本消息来源在内的许多消息来源,http://wiki.osdev.org/TCC
这应该有效:
struct some_struct {
unsigned char a __attribute__((packed));
unsigned char b __attribute__((packed));
} __attribute__((packed));
但它不起作用。