Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inline function linkage change

Tags:

c++

inline

linker

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?

like image 347
dongjk Avatar asked Jan 19 '23 06:01

dongjk


2 Answers

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.

like image 90
Employed Russian Avatar answered Jan 24 '23 14:01

Employed Russian


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

like image 45
parapura rajkumar Avatar answered Jan 24 '23 16:01

parapura rajkumar