Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unpredictable behavior of Inline functions with different definitions

Tags:

c++

gcc

I have the following source files:

//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();
}

and

//test2.cpp
#include <iostream>

using namespace std;

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

void bar()
{
    foo();
}

The output:

test1's foo
test1's foo

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?

EDIT: This is using gcc 4.4.1.

like image 247
user168715 Avatar asked Sep 17 '25 20:09

user168715


2 Answers

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

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

like image 171
R Samuel Klatchko Avatar answered Sep 19 '25 11:09

R Samuel Klatchko


R Samuel Klatchko's answer is correct, but I'll answer part that he didn't.

"And how does the compiler "see" the inline functions from across compilation units?"

It doesn't. It sees the external definitions of functions that are declared not to be static. For such functions, the compiler can inline if it wishes but it also has to generate code callable from outside.

like image 29
Windows programmer Avatar answered Sep 19 '25 09:09

Windows programmer