C行內函數的內外連結的區別
阿新 • • 發佈:2018-11-19
1.行內函數的內連結如inline static void fn(void) {} 沒有任何限制(建議使用)
2.行內函數的外連結如inline void fn(void) {} 則有諸多限制,最易被忽略的便是行內函數的外連結的定義(不僅需要.h檔案的替換體,還需要單獨的.c檔案存放extern inline void fn(void)的外部定義);另外,一個非 static 的行內函數不能定義一個非 const 的函式區域性 static 物件,並且不能使用檔案作用域的 static 物件。例如:
static int x;
inline void f(void) { static int n = 1; // 錯誤:非 const 的 static 物件在非 static 的 inline 函式中 int k = x; // 錯誤:非 static 的 inline 函式訪問 static 變數 }
示例程式碼:
// file test.h
#ifndef TEST_H_INCLUDED
#define TEST_H_INCLUDED
inline int sum (int a, int b) { return a+b; } #endif // 檔案 sum.c #include "test.h" extern inline int sum (int a, int b); // 提供外部定義 // 檔案 test1.c #include <stdio.h> #include "test.h" extern int f(void); int main(void) { printf("%d\n", sum(1, 2) + f()); } // 檔案 test2.c #include "test.h" int f(void) { return sum(2, 3); }