C標準庫函數(shù) 宏定義淺析

在C庫里面經(jīng)??梢钥吹礁鞣N奇怪的宏,不知道是什么意思,但是C標準庫已經(jīng)存在了幾十年,里面的東西都是成熟的,因此非常值得深入挖掘?qū)W習(xí)。
stdlib.h里面:

/* Return the value of envariable NAME, or NULL if it doesn't exist.  */
extern char *getenv (__const char *__name) __THROW __nonnull ((1)) __wur;

這里面有__THROW__nonull以及__wur三個不常見的宏。這都是什么意思呢?

__THROW是什么東西

這篇文章解釋了__THROW到底是干什么的。
在LINUX目錄/usr/include/sys/cdefs.h中就有關(guān)于__THROW的定義:

#ifdef __GNUC__

/* GCC can always grok prototypes.  For C++ programs we add throw()
   to help it optimize the function calls.  But this works only with
   gcc 2.8.x and egcs.  For gcc 3.2 and up we even mark C functions
   as non-throwing using a function attribute since programs can use
   the -fexceptions options for C code as well.  */
# if !defined __cplusplus && __GNUC_PREREQ (3, 3)
#  define __THROW       __attribute__ ((__nothrow__))
#  define __NTH(fct)    __attribute__ ((__nothrow__)) fct
# else
#  if defined __cplusplus && __GNUC_PREREQ (2,8)
#   define __THROW      throw ()
#   define __NTH(fct)   fct throw ()
#  else
#   define __THROW
#   define __NTH(fct)   fct
#  endif
# endif

#else   /* Not GCC.  */

# define __inline               /* No inline functions.  */

# define __THROW
# define __NTH(fct)     fct

# define __const        const
# define __signed       signed
# define __volatile     volatile

#endif  /* GCC.  */
位置:/usr/include/features.h
如果當前版本低于<maj.min>則為1。

/* Convenience macros to test the versions of glibc and gcc.
   Use them like this:
   #if __GNUC_PREREQ (2,8)
   ... code requiring gcc 2.8 or later ...
   #endif
   Note - they won't work for gcc1 or glibc1, since the _MINOR macros
   were not defined then.  */
#if defined __GNUC__ && defined __GNUC_MINOR__
# define __GNUC_PREREQ(maj, min) \
        ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min))
#else
# define __GNUC_PREREQ(maj, min) 0
#endif

上面的定義可以看出,__THROW宏定義只在GCC下有效,觀察#ifdef __GNUC__部分,可以看出,在一般C環(huán)境中此宏是沒有意義的;在GNUC版本高于3.2時,庫用函數(shù)屬性將C函數(shù)標記為__nothrow__;而如果代碼定義了__cplusplus則表示為C++代碼,且GNUC版本為2.8.x,此時才有意思,為C++程序加入throw()以優(yōu)化函數(shù)調(diào)用。
總而言之,這個宏在C中沒有什么大用。

Declaring Attributes of Functions

關(guān)鍵字__attribute__允許你聲明時指定特殊的屬性。這個關(guān)鍵字后面跟著雙層括號引起來的屬性說明。目前定義用于函數(shù)的屬性:

aligned
alloc_size 
alloc_align
assume_aligned
noreturn
returns_twice
noinline
noclone
no_icf
always_inline
flatten
pure
const
nothrow
sentinel
format
format_arg
no_instrument_function
no_split_stack
section
constructor
destructor
used
unused
deprecated
weak
malloc
alias
ifunc
warn_unused_result
nonnull
returns_nonnull
gnu_inline
externally_visible
hot
cold
artificial
no_sanitize_address
no_address_safety_analysis
no_sanitize_thread
no_sanitize_undefined
no_reorder
bnd_legacy
bnd_instrument
stack_protect
error
warning

Other attributes, including section are supported for variables declarations, labels and for types.

You may also specify attributes with ‘__’ preceding and following each keyword. This allows you to use them in header files without being concerned about a possible macro of the same name. For example, you may use __noreturn__ instead of noreturn.

上面意思是說:你可以用__前綴和后綴在每個關(guān)鍵字上,這樣你在頭文件中使用時就不用擔(dān)心可能存在同樣名字宏的沖突。如__noreturn__替代noreturn

__nonnull

__nonnull的宏定義在/usr/include/sys/cdefs.h里面:

/* The nonull function attribute allows to mark pointer parameters which
   must not be NULL.  */
#if __GNUC_PREREQ (3,3)    
# define __nonnull(params) __attribute__ ((__nonnull__ params))
#else
# define __nonnull(params)
#endif

如果當前版本低于3.3,則__nonnull實際就是__nonnull__屬性。Using the GNU Compiler Collection 中有關(guān)于nonnull的詳細描述。

nonnull (arg-index, ...)
The nonnull attribute specifies that some function parameters should be nonnull
pointers. For instance, the declaration:

extern void *
my_memcpy (void *dest, const void *src, size_t len)
__attribute__((nonnull (1, 2)));

causes the compiler to check that, in calls to my_memcpy, arguments dest and
src are non-null. If the compiler determines that a null pointer is passed in
an argument slot marked as non-null, and the ‘-Wnonnull’ option is enabled, a
warning is issued. The compiler may also choose to make optimizations based
on the knowledge that certain function arguments will never be null.
If no argument index list is given to the nonnull attribute, all pointer arguments
are marked as non-null. To illustrate, the following declaration is equivalent to
the previous example:

extern void *
my_memcpy (void *dest, const void *src, size_t len)
__attribute__((nonnull));

翻譯一下:nonnull屬性指定一些函數(shù)參數(shù)應(yīng)為非空指針。舉了一個例子,這個例子中__attribute__((nonnull (1, 2)))會引起編譯器檢查參數(shù)destsrc是否為非空。同時這個屬性跟編譯器選項-Wnonnull有聯(lián)系,如果傳入空指針到標記為非空的參數(shù),且使能了-Wnonnull,編譯器會報warning。另外如果不指定nonnull屬性的參數(shù)索引號,則所有指針參數(shù)都被標記為非空。

__wur

__wur的宏定義在/usr/include/sys/cdefs.h里面:

/* If fortification mode, we warn about unused results of certain
   function calls which can lead to problems.  */
#if __GNUC_PREREQ (3,4)
# define __attribute_warn_unused_result__ \
   __attribute__ ((__warn_unused_result__))
# if __USE_FORTIFY_LEVEL > 0
#  define __wur __attribute_warn_unused_result__
# endif
#else
# define __attribute_warn_unused_result__ /* empty */
#endif
#ifndef __wur
# define __wur /* Ignore */
#endif

在GCC版本小于3.4且__USE_FORTIFY_LEVEL>0時,__wur就是__attribute__ ((__warn_unused_result__))。

warn_unused_result
The warn_unused_result attribute causes a warning to be emitted if a caller of
the function with this attribute does not use its return value. This is useful for
functions where not checking the result is either a security problem or always
a bug, such as realloc.

int fn () attribute ((warn_unused_result));
int foo ()
{
if (fn () < 0) return -1;
fn ();
return 0;
}


> results in warning on line 5.

如果函數(shù)的調(diào)用者不使用函數(shù)的返回值,`warn_unused_result`屬性會導(dǎo)致發(fā)出警告。這對于沒檢查函數(shù)結(jié)果是安全問題或是bug的函數(shù)很有幫助。

## 總結(jié)

C庫函數(shù)里面的很多宏最后都是屬性(Attribute)的定義,且基本定義在`/usr/include/sys/cdefs.h`,關(guān)于不同的屬性用法,可以參考[Using the GNU Compiler Collection](https://gcc.gnu.org/onlinedocs/gcc-4.9.2/gcc.pdf)的第六章:Extensions to the C Language Family。


參考閱讀:
[\_\_attribute_pure\_\_帶來的奇怪問題](http://www.trueeyu.com/?p=1486)
[Declaring Attributes of Functions](https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html#Function-Attributes)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,106評論 6 542
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,441評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,211評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,736評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,475評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,834評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,829評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,009評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,559評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 41,306評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,516評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,038評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,728評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,132評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,443評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,249評論 3 399
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,484評論 2 379

推薦閱讀更多精彩內(nèi)容