天天看點

inline使用注意事項

文章目錄

GCC

在不優化時不會内聯任何函數,除非指定函數的“

always_inline

”屬性。

先附上結論:

GCC

在不優化時不會内聯任何函數,除非指定函數的“

always_inline

”屬性。

測試代碼:

#include <stdio.h>

inline void say(void) {
    printf("Hello, World\n");
}

int main(void) {
    say();
    return 0;
}
           

使用

-O3

優化選項,一切正常:

$ gcc -O3 -o test_O3.o -c test.c
$ g++ test_O3.o -o test_O3
$ ./test_O3
Hello, World
           

使用

-O0

優化選項,連結時報錯,提示找不到内聯函數

say

$ gcc -O0 -o test_O0.o -c test.c
$ g++ test_O0.o -o test_O0
test_O0.o: In function `main':
test.c:(.text+0x5): undefined reference to `say'
collect2: error: ld returned 1 exit status
           

分别檢視檔案

test_O0.o

test_O3.o

$ readelf -s test_O0.o

Symbol table '.symtab' contains 10 entries:
   Num:    Value          Size Type    Bind   Vis      Ndx Name
     0: 0000000000000000     0 NOTYPE  LOCAL  DEFAULT  UND 
     1: 0000000000000000     0 FILE    LOCAL  DEFAULT  ABS test.c
     2: 0000000000000000     0 SECTION LOCAL  DEFAULT    1 
     3: 0000000000000000     0 SECTION LOCAL  DEFAULT    3 
     4: 0000000000000000     0 SECTION LOCAL  DEFAULT    4 
     5: 0000000000000000     0 SECTION LOCAL  DEFAULT    6 
     6: 0000000000000000     0 SECTION LOCAL  DEFAULT    7 
     7: 0000000000000000     0 SECTION LOCAL  DEFAULT    5 
     8: 0000000000000000    16 FUNC    GLOBAL DEFAULT    1 main
     9: 0000000000000000     0 NOTYPE  GLOBAL DEFAULT  UND say
           
$ readelf -s test_O3.o

Symbol table '.symtab' contains 13 entries:
   Num:    Value          Size Type    Bind   Vis      Ndx Name
     0: 0000000000000000     0 NOTYPE  LOCAL  DEFAULT  UND 
     1: 0000000000000000     0 FILE    LOCAL  DEFAULT  ABS test.c
     2: 0000000000000000     0 SECTION LOCAL  DEFAULT    1 
     3: 0000000000000000     0 SECTION LOCAL  DEFAULT    2 
     4: 0000000000000000     0 SECTION LOCAL  DEFAULT    3 
     5: 0000000000000000     0 SECTION LOCAL  DEFAULT    4 
     6: 0000000000000000     0 SECTION LOCAL  DEFAULT    5 
     7: 0000000000000000     0 SECTION LOCAL  DEFAULT    6 
     8: 0000000000000000     0 SECTION LOCAL  DEFAULT    9 
     9: 0000000000000000     0 SECTION LOCAL  DEFAULT   10 
    10: 0000000000000000     0 SECTION LOCAL  DEFAULT    8 
    11: 0000000000000000    21 FUNC    GLOBAL DEFAULT    6 main
    12: 0000000000000000     0 NOTYPE  GLOBAL DEFAULT  UND puts
           

可以發現檔案

test_O0.o

中,

inline

修飾的函數

say

為未定義狀态,說明

inline

函數并沒有展開。

指定

say

函數為“

always_inline

”屬性:

#include <stdio.h>

__attribute__((always_inline)) inline void say(void) {
    printf("Hello, World\n");
}

int main(void) {
    say();
    return 0;
}
           

重新使用

-O0

優化選項編譯運作,一切

ok

$ gcc -O0 -o test.o -c test.c
$ gcc -O0 -o test_O0_2.o -c test.c
$ g++ test_O0_2.o -o test_O0_2
$ ./test_O0_2
Hello, World
           

微信公衆号同步更新,微信搜尋"AnSwEr不是答案"或者掃描二維碼,即可訂閱。

inline使用注意事項
  • GitHub:AnSwErYWJ
  • Blog:http://www.answerywj.com
  • Email:[email protected]
  • Weibo:@AnSwEr不是答案