簡體   English   中英

內聯函數如何在C ++中工作?

[英]how does the inline function work in C++?

現在我有2個c ++源文件:test9.cpp test10.cpp,它們都有一個同名的內聯函數。

test9.cpp:

1 #include <iostream>
2 using namespace std;
3 void test();
4 inline void f1()
5 {
6     cout << "inline f1 in test9.cpp" << endl;
7 }   
8 int main()
9 {
10     f1();
11     test();
12     return 0;
13 } 

test10.cpp:

1 #include <iostream>
2 using namespace std;
3 inline void f1()
4 {
5     cout << "inline f1 in test10.cpp" << endl;
6 }   
7 void test()
8 {
9     f1();
10 } 

現在用g ++編譯它們:g ++ test9.cpp test10.cpp ./a.out我得到以下結果:

inline f1 in test9.cpp
inline f1 in test9.cpp

怎么了? 我以為它會是:“test10.cpp中test9.cpp內聯f1中的內聯f1”誰能告訴我為什么? g ++編譯器如何處理內聯函數?

雖然編譯器允許您(不, 需要您!)重新定義inline標記的函數,但外部鏈接的默認值仍然適用,因此您違反了一個定義規則。 這會導致未定義的行為和您看到的結果。

[C++11: 7.1.2/4]:內聯函數應在每個使用過的翻譯單元中定義,並且在每種情況下都應具有完全相同的定義(3.2)。 [..]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM