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

c – 具有不同定义的内联函数的不可预测行为

发布时间:2020-12-16 10:39:13 所属栏目:百科 来源:网络整理
导读:我有以下源文件: //test1.cpp#include iostreamusing namespace std;inline void foo(){ cout "test1's foo" endl;}void bar();int main(int argc,char *argv[]){ foo(); bar();} 和 //test2.cpp#include iostreamusing namespace std;inline void foo(){ c
我有以下源文件:

//test1.cpp
#include <iostream>
using namespace std;

inline void foo()
{
  cout << "test1's foo" << endl;
}

void bar();

int main(int argc,char *argv[])
{
  foo();
  bar();
}

//test2.cpp
#include <iostream>

using namespace std;

inline void foo()
{
    cout << "test2's foo" << endl;
}

void bar()
{
    foo();
}

输出:

test1's foo
test1's foo

咦???好的,所以我应该声明foos是静态的…但是这种事情不应该产生链接器错误,或者至少是警告?编译器如何从编译单元“看到”内联函数?

编辑:这是使用gcc 4.4.1.

解决方法

您正在运行 one-definition-rule.您没有看到任何错误,因为:

[Some] violations,particularly those that span translation units,are not required to be diagnosed

在幕后发生的事情是编译器没有内联这些函数(除非使用优化器编译代码,否则许多编译器不会内联函数).由于函数是内联的并且可以出现在多个转换单元中,因此编译器会将该函数标记为link-once,它告诉链接器它不会将多个定义视为错误,而只是使用其中一个.

如果你真的希望它们不同,你需要一个静态函数.

(编辑:李大同)

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

    推荐文章
      热点阅读