具有不同定义的Inline函数的不可预测的行为 [英] unpredictable behavior of Inline functions with different definitions

查看:98
本文介绍了具有不同定义的Inline函数的不可预测的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下源文件:

//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静态...但不应该这种事情生成链接器错误,或至少一个警告?编译器如何从编译器中看到内联函数?

Huh??? Ok, so I should have declared the foos static... but shouldn't this kind of thing generate a linker error, or at least a warning? And how does the compiler "see" the inline functions from across compilation units?

编辑:这是使用gcc 4.4.1。

This is using gcc 4.4.1.

推荐答案

您正在使用 one-definition-规则。您没有看到任何错误,因为:

You are running into the one-definition-rule. You are not seeing any error because:


无需诊断某些违规行为, p>

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

下面是编译器不内联这些函数(许多编译器不会内联函数,除非代码是编译的优化器)。由于函数是内联的并且可以出现在多个翻译单元中,编译器会将函数标记为链接一次,这告诉链接器它不会将多个定义视为错误,而只是使用其中一个。

What going on under the covers is that the compiler is not inlining those functions (many compilers will not inline a function unless the code is compiled with the optimizer). Since the function is inline and can appear in multiple translation units, the compiler will mark the function as link-once which tells the linker that it not treat multiple definitions as an error but just use one of them.

如果你真的想让它们不同,你需要一个静态函数。

If you really want them to be different, you want a static function.

这篇关于具有不同定义的Inline函数的不可预测的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆