前幾天Peter說要定義程式撰寫規範,讓公司內部產出的程式比較有統一的style,也比較能避免問題的產生。 /* #include<stdio.h> struct BAD_STRU struct FIELD_STRU_1{ struct FIELD_STRU_2{ struct PADDING_STRU{ /* third flag */ void showSize(){ printf("BIT FIELD COMPARE:\n"); int main(int argc, char* argv[]){
我們收到了一個excel檔,裡面定義了一大堆的規範,有的淺顯易懂,有的則是語焉不詳,因此必須要有一些sample,來讓大家瞭解。當然,會出現這篇文章,就表示這工作掉到了我們的身上。
我負責了六個sample的撰寫,有的很簡單,但也有些是我原本不清楚的,就一個個來看吧。
Topic : 仔細設計struct中元素的佈局與排列順序,使struct容易理解、節省佔用空間,並減少引起誤用現象。
Description : 合理排列struct中元素順序,可節省空間並增加可理解性。
Example :
* sample-59
* This sample shows how to declare structure members,
* especially in encounter bit field.
*
* To improve readability and strip program size
* notice the sequence of the structure members.
*
*/
{
unsigned int valid: 1; // 1/32 bytes, 1 bit field
int x; // 4 bytes
unsigned int set_flg: 1; // 1/32 bytes, 1 bit field
}bad;
struct GOOD_STRU
{
unsigned int valid: 1; // 1/32 bytes, 1 bit field
unsigned int set_flg: 1; // 1/32 bytes, 1 bit field
int x; // 4 bytes
}good;
unsigned int is_keyword: 1; // 1/32 bytes, 1 bit field
unsigned int is_extern: 1; // 1/32 bytes, 1 bit field
unsigned int is_static: 1; // 1/32 bytes, 1 bit field
}field_1_byte;
unsigned int is_keyword: 1; // 1/32 bytes, 1 bit field
unsigned int is_extern: 1; // 1/32 bytes, 1 bit field
unsigned int is_static: 1; // 1/32 bytes, 1 bit field
unsigned int over_bits: 30; // 30/32 bytes, 30 bit fields
}field_2_byte;
/* first flag */
unsigned int first_flag_1: 1; // 1/32 bytes, 1 bit field
unsigned int first_flag_2: 1; // 1/32 bytes, 1 bit field
unsigned int: 30; // pad 30 bit fields
/* second flag */
unsigned int second_flag_1: 1; // 1/32 bytes, 1 bit field
unsigned int: 0; // The special width 0 may be used to
// force alignment at the next word boundary
unsigned int third_flag: 1; // 1/32 bytes, 1 bit field
}pad;
printf("STRUCTURE COMPARE:\n");
printf("\tsizeof(struct BAD_STRU)\t\t: %d\n", sizeof(bad));
printf("\tsizeof(struct GOOD_STRU)\t: %d\n", sizeof(good));
printf("\tsizeof(struct FIELD_STRU_1)\t: %d\n", sizeof(field_1_byte));
printf("\tsizeof(struct FIELD_STRU_2)\t: %d\n", sizeof(field_2_byte));
printf("\tsizeof(struct PADDING_STRU)\t: %d\n", sizeof(pad));
}
showSize();
return 0;
}
這個 sample 是在提醒我們要注意變數宣告時的記憶體配置,經過適當的調整後,可以讓程式compile後產出的binary更小。
風花水月六十石
15 年前
沒有留言:
張貼留言