我正在尝试在tcc压缩机中完成打包结构。代码如下所示,应该支持__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 __((打包))和其他几个测试--都没有用。
发布于 2015-02-21 17:08:50
正如您已经发现的,__attribute__ 扩展只适用于struct的成员,因此每个成员都应该单独应用它。下面是带有小适应的代码,它使用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但是,有了头,__attribute__就不再工作了。我不确定这种情况是否总是发生,但在我的系统(CentOS 6)上,它正是这样做的。
正如我所发现的,解释位于内部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)编写人员之间的不一致。
发布于 2017-05-22 18:15:24
我可以确认,至少使用tcc 0.9.26对struct成员的attribute((packed))是不工作的。使用Windows风格的打包实用程序工作得很好:
#if defined(__TINYC__)
#pragma pack(1)
#endif
typedef struct {
uint16_t ..
} interrupt_gate_descriptor_t;
#if defined(__TINYC__)
#pragma pack(1)
#endif发布于 2015-02-20 21:26:02
似乎是TCC的错误。
根据许多消息来源,包括这个消息,http://wiki.osdev.org/TCC
这应该是可行的:
struct some_struct {
unsigned char a __attribute__((packed));
unsigned char b __attribute__((packed));
} __attribute__((packed));..。但不起作用。
https://stackoverflow.com/questions/28637879
复制相似问题