1. 程式人生 > 其它 >minGW: 記錄windows下minGW的一個問題

minGW: 記錄windows下minGW的一個問題

如下所示:

#include <stdio.h>
 
/*編譯器預設是4位元組對齊*/
struct test{
    char a;
    int b;
};
 
/*按實際佔用的空間大小*/
struct test1{
    char a;
    int b;
}__attribute__((packed));
 
/*結構體大小必須4位元組對齊*/
struct test2{
    char a;
    int b;
}__attribute__((aligned(4)));
 
/*結構體大小必須8位元組對齊*/
struct test3{
    char a;
    int
b; }__attribute__((aligned(8))); /*結構體大小必須16位元組對齊*/ struct test4{ char a; int b; }__attribute__((aligned(16))); /*int 型別資料大小必須8位元組對齊*/ struct test5{ char a; int __attribute__((aligned(8))) b; }; int main() { printf("test:%d\n",sizeof(struct test)); printf("test1:%d\n",sizeof
(struct test1)); printf("test2:%d\n",sizeof(struct test2)); printf("test3:%d\n",sizeof(struct test3)); printf("test4:%d\n",sizeof(struct test4)); printf("test5:%d\n",sizeof(struct test5)); return 0; }

struct test1本以為會佔用5個位元組,但是使用minGW編譯執行後,發現實際輸出的結果如下:

[Running]cd"c:\Users\nisha_chen\Desktop\byteAlign\"&&gccbyte_align.c-obyte_align&&"c:\Users\nisha_chen\Desktop\byteAlign\"byte_align test:8 test1:8
test2:8 test3:8 test4:16 test5:16 實際佔用長度為8個位元組,把上述code複製到linux下編譯執行後,提到的結果仍為 5個位元組,說明code本身是沒有問題的。參考了一些連結,有說是minGW bug的,有說是寫法有問題的。 1.C/C++ struct packing not working 2.Struct packing and alignment with mingw 3.MinGW-w64 - for 32 and 64 bit Windows 不過看到有一個寫法可能得到正確的結果:

attribute packed isbroken on mingw32 compilers. Another option is to usepragma pack:

#pragma pack(1)
typedef struct _file
{
  uint8_t var1;
  uint16_t var2;
} FILE;

就是加上 #pragma pack(1)。