4

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 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

a weak symbol was added when there is a call func of the inline func, see: 00000000 **W** _Z2f1ii
4

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

2 Comments

ok, I use -std=c++98 to try again, but it still passed... why?
In 9.2 of c++98... it states that combination of external linkage and inlining is banned to make life simpler for compiler writers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.