现在的位置: 首页 > 综合 > 正文

往arm平台移植应用程序 时候遇到的一个关于字节对齐问题

2013年08月28日 ⁄ 综合 ⁄ 共 598字 ⁄ 字号 评论关闭
往arm平台移植应用程序 时候遇到的一个关于字节对齐问题

例子:
定义一个类如下:
class Example {
public:
    Example();
private:
    unsigned short c;
} ;

由于unsigned short 是两个字节,所以在PC上该类只占2个字节,
而在arm平台上,由于4字节对齐问题,所以该类就变成4字节了,
所以在arm当该类指针++时,就会出现问题。:)

解决方法可以在编译arm平台程序时候该类加上 __attribute__((packed)) 参数。

测试代码:

#include <stdio.h>
#define PLATFORM_ARM 0

class Example
{
    public:
        unsigned short c;

#if PLATFORM_ARM
}__attribute__((packed));
#else
};
#endif

int main(void)
{
    Example  *exm= new Example ;

#if PLATFORM_ARM
    printf("on arm  /n");
#else
    printf("on pc   /n");
#endif
    printf("the sizeof class  Example is [%d], pointer is [%d]/n"
            ,sizeof(Example ),sizeof(exm));

    return 0;

}

抱歉!评论已关闭.