简体   繁体   English

内联函数如何在C ++中工作?

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

now I have 2 c++ source files: test9.cpp test10.cpp, they both have a inline function with the same name. 现在我有2个c ++源文件:test9.cpp test10.cpp,它们都有一个同名的内联函数。

test9.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: 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 } 

now compile them with g++: g++ test9.cpp test10.cpp ./a.out I get the following result: 现在用g ++编译它们:g ++ test9.cpp test10.cpp ./a.out我得到以下结果:

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

what's wrong? 怎么了? I thought it would be: "inline f1 in test9.cpp inline f1 in test10.cpp" who can tell me why? 我以为它会是:“test10.cpp中test9.cpp内联f1中的内联f1”谁能告诉我为什么? how does the g++ compiler treats the inline function? g ++编译器如何处理内联函数?

While the compiler will allow you (nay, require you!) to redefine functions marked inline , the default of external linkage still applies, so you are breaking the One Definition Rule. 虽然编译器允许您(不, 需要您!)重新定义inline标记的函数,但外部链接的默认值仍然适用,因此您违反了一个定义规则。 This results in undefined behaviour and the outcome that you are seeing. 这会导致未定义的行为和您看到的结果。

[C++11: 7.1.2/4]: An inline function shall be defined in every translation unit in which it is odr-used and shall have exactly the same definition in every case (3.2). [C++11: 7.1.2/4]:内联函数应在每个使用过的翻译单元中定义,并且在每种情况下都应具有完全相同的定义(3.2)。 [..] [..]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM