用__attribute__((deprecated))管理過時的代碼

在開發一些庫的時候,API的接口可能會過時,爲了提醒開發者這個函數已經過時。可以在函數聲明時加上attribute((deprecated))屬性,如此,只要函數被使用,在編譯是都會產生警告,警告信息中包含過時接口的名稱及代碼中的引用位置。

attribute可以設置函數屬性(Function Attribute)、變量屬性(Variable Attribute)和類型屬性(Type Attribute)。
attribute語法格式爲:attribute ((attribute))
注意: 使用attribute的時候,只能函數的聲明處使用attribute

#include <stdio.h>
#include <stdlib.h>

#ifdef __GNUC__
#    define GCC_VERSION_AT_LEAST(x,y) (__GNUC__ > (x) || __GNUC__ == (x) && __GNUC_MINOR__ >= (y))
#else
#    define GCC_VERSION_AT_LEAST(x,y) 0
#endif

#if GCC_VERSION_AT_LEAST(3,1)
#    define attribute_deprecated __attribute__((deprecated))
#elif defined(_MSC_VER)
#    define attribute_deprecated __declspec(deprecated)
#else
#    define attribute_deprecated
#endif


/* Variable Attribute */
attribute_deprecated int  variable_old = 0;

/* Function Attribute */
attribute_deprecated void function_old(void);

void function_old(void)
{
    printf("old function.\n");
    return;
}

int main(void)
{
    variable_old++;

    function_old();

    return EXIT_SUCCESS;
}

在編譯時會出現類似警告:

# gcc attribute_deprecated.c -o test
attribute_deprecated.c: In function ‘main’:
attribute_deprecated.c:33: warning: ‘variable_old’ is deprecated (declared at attribute_deprecated.c:20)
attribute_deprecated.c:35: warning: ‘function_old’ is deprecated (declared at attribute_deprecated.c:25)

發佈了90 篇原創文章 · 獲贊 351 · 訪問量 150萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章