c - tcc 中的打包结构

标签 c struct tcc packed

我正在尝试在 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/

相关文章:

c++ - 适用于 Windows 的良好 c/c++ 编译器

arrays - 使用Hive在数组中创建结构

c - 将指向结构的指针分配给变量

c - 如何修复 Build TinyCCompiler(TCC) from Source 中的 Error of crt1.o,crti.o?

c - 如何读取平面文件并将数据放入相应的变量

c - 为什么这个for循环不执行?

c - 明智地遍历区间内的数字

c++ - 如何读取大量数字?

c - 从二进制文件读取结构并转换为C中的十六进制

c++ - 尝试使用 tcc 针对 gcc 生成的 .o 文件编译源代码时出现奇怪的行为