在tcc中打包的结构

时间:2015-02-20 20:47:02

标签: c struct tcc packed

我正在尝试在tcc C compiller中执行压缩结构。 代码如下,并且应支持__attribute __ tag:

#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))和其他一些测试 - 没有用。

3 个答案:

答案 0 :(得分:2)

正如您已经发现__attribute__ extension仅适用于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__类似函数的宏被#34;冲洗了#34;对于tcc,因为它没有定义__GNUC__宏。 tcc开发人员与标准库(此处为glibc)作者之间似乎有些不连贯。

答案 1 :(得分:0)

似乎是TCC的错误。

根据许多来源,包括这一个,http://wiki.osdev.org/TCC

这应该有效:

struct some_struct {
   unsigned char a __attribute__((packed));
   unsigned char b __attribute__((packed));
} __attribute__((packed));

......但它不起作用。

答案 2 :(得分:0)

我可以确认至少使用tcc 0.9.26 属性((打包)) struct成员无法正常工作。使用Windows风格的打包pragma工作得很好:

    #if defined(__TINYC__)
    #pragma pack(1)
    #endif

    typedef struct {
            uint16_t ..
    } interrupt_gate_descriptor_t;

    #if defined(__TINYC__)
    #pragma pack(1)
    #endif
相关问题