4
votes

I just created two file to test the inline function's linkage, the first one

#include <iostream>
using namespace std;
inline int f1(int a,int b){
  a=a+b;
  while(a!=0)
    a--;
  cout<<"inline";
  return a;
}

the second one:

int main(){
  extern void f1(int a,int b);
  f1(1,2);
}

g++ frist.cc second.cc

undefined reference to `f1(int, int)'

linker raise a error, as i expect the inline function is default internal linkage so the result is right.


but, when I add a call function of the inline function to the first file:

#include <iostream>
using namespace std;
inline int f1(int a,int b){
  a=a+b;
  while(a!=0)
    a--;
  cout<<"inline";
  return a;
}
int callf1(){
  f1(10,2);
}

and compile again, it passed, and can run without error, so I want ask what had happened here?

2

2 Answers

5
votes

what had happened here?

When a compiler compiles an inline function, it may choose to inline it or not, depending on a number of heuristics, and on current optimization level. The inline is only a suggestion, which the compiler is free to ignore at will.

If the compiler decides not to inline the function, then it will emit an actual function definition (just as if the function was not declared inline), with weak linkage (so that multiple such definitions do not cause a problem). That is what's happening, and why your program links.

Your program may stop linking if you crank up optimization level, or use a compiler with different inlining heuristics.

4
votes

In C++ if a function is defined as inline somewhere, it has be to so everywhere

from C++ 7.1.2

An inline function shall be defined in every translation unit in which it is used and shall have exactly the same definition in every case (3.2)

3.2 refers to the One Definition Rule

So what you are experiencing is non C++ standard behavior