Change the built-in communication function

I just created two files to test the built-in link function, the first

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

second:

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

g ++ frist.cc second.cc

 undefined reference to `f1(int, int)' 

linker throws an error since I expect the inline function to be the default internal link, so the result is correct.


but when I add the function call the built-in 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 went through and can work without errors, so I want to ask what happened here?

+4
source share
2 answers

what happened here?

When the compiler compiles a built-in function, it can choose whether it is built-in or not, depending on the number of heuristics and the current level of optimization. inline is just a sentence that the compiler can ignore at its discretion.

If the compiler decides not to embed the function, then it gives the actual definition of the function (just as if the function had not been declared inline), with weak coupling (so that several such definitions do not pose a problem). This is what happens and why your program is connected.

Your program may stop communicating if you increase the level of optimization or use a compiler with various insert heuristics.

+5
source

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

from C ++ 7.1.2

The built-in function must be defined in each translation unit in which it is used, and must have exactly the same definition in each case (3.2)

3.2 relates to the rule of one definition

So what are you experiencing is standard behavior different from C ++

+4
source

Source: https://habr.com/ru/post/1381416/


All Articles