minGW: 記錄windows下minGW的一個問題
阿新 • • 發佈:2021-09-03
如下所示:
#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; intb; }__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:8attribute 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)。