【问题标题】:How to declare packed struct (without padding) for LLVM?如何为 LLVM 声明打包结构(无填充)?
【发布时间】:2012-11-21 05:39:55
【问题描述】:

可以告诉 GCC 它不应该对结构使用填充。这是使用__attribute__((packed)) 完成的。

typedef struct {

  uint8_t startSymbol;
  uint8_t packetType;
  uint32_t deviceId;
  uint16_t packetCRC;

} PacketData __attribute__((packed));

但是,最新的 Xcode 使用 LLVM 并且无法识别该属性。如何为 LLVM 定义打包结构?

问题的完整描述可以在here找到

更新 我正在使用适用于 iOS 的 Xcode 4.5.1,它使用 Apple LLVM 4.1 编译器。在上面的代码示例中,我在 Xcode 中收到“'packed' attribute ignored”警告。

【问题讨论】:

  • 我是否遗漏了什么或者这是一个非常新的功能删除?上次查,clang支持__attribute__((packed))...
  • clang 支持完全相同的__attribute__((packed)) pragma...
  • 不知道 :) 我正在使用 Xcode 4.5.1 for iOS,它使用 Apple LLVM 4.1 编译器。
  • @Centurion 我找到了答案,请参阅编辑。

标签: objective-c c struct


【解决方案1】:

您可以使用预处理器指令为结构指定字节对齐方式,因此编译器不会进行填充:

#pragma pack(1)

typedef struct {
char        t1;
long long   t2;
char        t3;
} struct_size_test;

#pragma options align=reset

在 stackoverflow 上查看this 问题的答案。

【讨论】:

    【解决方案2】:

    Linux 上的clang 3.5 -

    typedef struct __attribute__((packed)) thing1 { int blah; } THING_ONE;

    工作。

    【讨论】:

    • 已经有一个答案说明了这一点,为什么还要添加另一个?
    • 我相信在 ((packed)) 和 "{ int blah; }" 之间包含 (name?) 是不同的。
    【解决方案3】:

    你真的试过了吗?我刚刚在我的机器上测试了它,__attribute__((packed)) 使用clang 编译得很好。

    编辑:我收到了同样的警告(“警告:未使用的打包属性”)

    typedef struct {
        int a;
        char c;
    } mystruct __attribute__((packed));
    

    在这种情况下,sizeof(mystruct) 是 8。

    然而,

    typedef struct __attribute__((packed)) {
        int a;
        char c;
    } mystruct;
    

    工作得很好,sizeof(mystruct) 是 5。

    结论:似乎该属性需要在结构标签之前才能使其正常工作。

    【讨论】:

    • 是的,我刚刚做了。我正在使用 Xcode 4.5.1 for iOS,它使用 Apple LLVM 4.1 编译器。我在 Xcode 中收到“'packed' 属性被忽略”警告
    • @Centurion 然后检查sizeof(PacketData) 以查看警告是否没有实际意义。 Linux 上的 Clang 可以很好地处理编译指示。
    • @Centurion 这不意味着它被识别/支持只是没有使用吗?您实际上是在代码中的任何位置实例化结构吗?
    • @Centurion 没问题,我很高兴能帮上忙。 :)
    • 把它放在最后一行也可以:"} __attribute__((packed)) mystruct;"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多