2015-07-28 56 views
0

這個問題與GLib for c programming有關。 原代碼在這裏: https://github.com/GNOME/glib/blob/master/glib/gslice.hGLib宏g_slice_new問題

在glist.h,我看到了宏觀_g_list_alloc0,我想知道它是怎麼implements.So我回到正軌。

#define _g_list_alloc0() g_slice_new0 (GList) 

接着,反向跟蹤到宏g_slice_new0

#define g_slice_new0(type) ((type*) g_slice_alloc0 (sizeof (type))) 

好吧,反向跟蹤到

gpointer g_slice_alloc0 (gsize block_size) G_GNUC_MALLOC G_GNUC_ALLOC_SIZE(1); 

對於G_GNUC_MALLOC,我發現它居然是:

#define G_GNUC_MALLOC __attribute__((__malloc__)) 
#define G_GNUC_ALLOC_SIZE(x) __attribute__((__alloc_size__(x))) 

我對la很困惑st兩個宏G_GNUC_MALLOC和G_GNUC_ALLOC_SIZE。

我可以用替換G_GNUC_ALLOC_SIZE(1)和G_GNUC_MALLOC:

__attribute__((__alloc_size__(1))) 
__attribute__((__malloc__)) 

所以,更換宏觀

gpointer g_slice_alloc0 (gsize block_size) G_GNUC_MALLOC G_GNUC_ALLOC_SIZE(1); 

宏實際上定義這樣的:

gpointer g_slice_allo0 (gsize block_size) 
__attribute__((__malloc__)) __attribute__((__alloc_size__(1))) 

我的問題: 什麼表達

__attribute__((__malloc__)) __attribute__((__alloc_size__(1))) 

工作或生成?我猜它可以像

malloc(sizeof()) 

它根據sizeof分配內存。 爲什麼不使用malloc(sizeof())而不是這個完成的表達式? 什麼是

__attribute__ 

?它是否是glib的一個保留關鍵字?

gpointer g_slice_alloc0 (gsize block_size) G_GNUC_MALLOC G_GNUC_ALLOC_SIZE(1); 

表達式的類型是什麼?它不是宏或typedef。 這是一個以函數名爲宏的函數嗎? 任何人都可以爲我分析它?

原路段的位置: https://github.com/GNOME/glib/blob/master/glib/gslice.h

回答

3

你可以閱讀有關的屬性在這裏:https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html

malloc一個「告訴編譯器,函數是malloc的狀」。 alloc_size「用於告訴編譯器函數返回值指向內存,其中大小由一個或兩個函數參數給出。」

這一切都是爲了編譯器的優化。這些屬性不會改變函數的工作方式,只會讓編譯器產生更好的輸出。

0
#define G_GNUC_ALLOC_SIZE(x) __attribute__((__alloc_size__(x))) 

展開爲GNU C alloc_size功能屬性,如果編譯器是一個新的足夠的gcc。該屬性告訴編譯器該函數返回一個指向由第x個函數參數指定大小的內存的指針。

#define G_GNUC_MALLOC __attribute__((__malloc__)) 

展開爲GNU C malloc函數屬性如果編譯器是gcc。將函數聲明爲malloc可以更好地優化函數。如果函數返回一個指針,該指針在函數返回時保證不與別的指針發生別名(實際上,這意味着新分配的內存),則函數可以具有malloc屬性。