长长的对齐问题(MSVC与GCC) [英] long long alignment problem (MSVC vs. GCC)

查看:152
本文介绍了长长的对齐问题(MSVC与GCC)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在编写C跨平台的库,但最终我在我的单元测试有错误,但只能在Windows机器上。我跟踪这个问题,并发现这是关系到结构调整(我使用的是结构数组持有的多个相似对象的数据)。现在的问题是:memset的(的sizeof(结构)),并设置结构成员一个接一个产生不同的字节到字节的结果,因此memcmp()返回不等于的结果。

I'm writing C cross-platform library but eventually I've got error in my unittests, but only on Windows machines. I've tracked the problem and found it's related to alignment of structures (I'm using arrays of structures to hold data for multiple similar objects). The problem is: memset(sizeof(struct)) and setting structures members one by one produce different byte-to-byte result and therefore memcmp() returns "not equal" result.

下面的$ C $下图:

Here the code for illustration:

#include <stdio.h>
#include <string.h>

typedef struct {
    long long      a;
    int            b;
} S1;

typedef struct {
    long           a;
    int            b;
} S2;

S1 s1, s2;

int main()
{
    printf("%d %d\n", sizeof(S1), sizeof(S2));

    memset(&s1, 0xFF, sizeof(S1));
    memset(&s2, 0x00, sizeof(S1));

    s1.a = 0LL; s1.b = 0;

    if (0 == memcmp(&s1, &s2, sizeof(S1)))
        printf("Equal\n");
    else
        printf("Not equal\n");

    return 0;
}

下面的输出这code与2003年MSVC @的Windows产品:

This code with MSVC 2003 @ Windows produce following output:

16 8
Not equal

但是,同样的code与GCC 3.3.6 @ Linux的按预期工作:

But the same code with GCC 3.3.6 @ Linux works as expected:

12 8
Equal

这让我的单元测试非常辛苦。

This makes my unit-testing very hard.

我是否理解正确的是MSVC使用最大的原生型(久长)的大小来确定,以结构调整​​?

Am I understand correctly that MSVC uses size of biggest native type (long long) to determine alignment to structure?

有人可以给我意见,我怎样才能改变我的code,使之对这种奇怪的排列问题,更强大的?在我真正的code,我通过通用指针正与结构数组来执行的memset / memcmp,我通常不知道确切的类型,我只有的sizeof(结构)的价值。

Can somebody give me advice how can I change my code to make it more robust against this strange alignment problem? In my real code I'm working with arrays of structures via generic pointers to execute memset/memcmp and I'm usually don't know exact type, I have only sizeof(struct) value.

推荐答案

我们所做的是使用的#pragma包到指定的对象有多大应该是:

What we have done is used the #pragma pack to specify how big the objects should be:

#pragma pack(push, 2)

typedef struct {
    long long      a;
    int            b;
} S1;

typedef struct {
    long           a;
    int            b;
} S2;

#pragma pack(pop)

如果你做到这一点,结构是相同的尺寸在这两个平台。

If you do this, the structures will be the same size on both platforms.

这篇关于长长的对齐问题(MSVC与GCC)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆