加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 09:49:33 所属栏目:百科 来源:网络整理
导读:现在我有2个c源文件:test9.cpp test10.cpp,它们都有一个同名的内联函数. test9.cpp: 1 #include iostream2 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 retur
现在我有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 inline f1中的内联f1”
谁能告诉我为什么? g编译器如何处理内联函数?

解决方法

虽然编译器允许您(不,需要您!)重新定义内联标记的函数,但外部链接的默认值仍然适用,因此您违反了一个定义规则.这会导致未定义的行为和您看到的结果.

[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). [..]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读