首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >tcc中的填充结构

tcc中的填充结构
EN

Stack Overflow用户
提问于 2015-02-20 20:47:02
回答 3查看 683关注 0票数 2

我正在尝试在tcc压缩机中完成打包结构。代码如下所示,应该支持__attribute __标记:

代码语言:javascript
复制
#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 __((打包))和其他几个测试--都没有用。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-02-21 17:08:50

正如您已经发现的,__attribute__ 扩展只适用于struct的成员,因此每个成员都应该单独应用它。下面是带有小适应的代码,它使用tcc 0.9.26编译,然后以正确的输出运行:

代码语言:javascript
复制
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;
}

结果:

代码语言:javascript
复制
4
  0 cc
  1 bb
  2 aa
  3 dd

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

代码语言:javascript
复制
#include <stdio.h>
#include <stdint.h> // then replace unsigned short with uint16_t

但是,有了头,__attribute__就不再工作了。我不确定这种情况是否总是发生,但在我的系统(CentOS 6)上,它正是这样做的。

正如我所发现的,解释位于内部sys/cdefs.h头中,其中包含:

代码语言:javascript
复制
/* 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)编写人员之间的不一致。

票数 2
EN

Stack Overflow用户

发布于 2017-05-22 18:15:24

我可以确认,至少使用tcc 0.9.26对struct成员的attribute((packed))是不工作的。使用Windows风格的打包实用程序工作得很好:

代码语言:javascript
复制
    #if defined(__TINYC__)
    #pragma pack(1)
    #endif

    typedef struct {
            uint16_t ..
    } interrupt_gate_descriptor_t;

    #if defined(__TINYC__)
    #pragma pack(1)
    #endif
票数 1
EN

Stack Overflow用户

发布于 2015-02-20 21:26:02

似乎是TCC的错误。

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

这应该是可行的:

代码语言:javascript
复制
struct some_struct {
   unsigned char a __attribute__((packed));
   unsigned char b __attribute__((packed));
} __attribute__((packed));

..。但不起作用。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28637879

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档