here is the code a1.cpp
#include <stdio.h>
void func(void)
{
printf("hello world\n");
}
int main()
{
func();
return 0;
}
here is the code a2.cpp
#include <stdio.h>
inline void func(void)
{
printf("hello world\n");
}
int main()
{
func();
return 0;
}
they are only different with the key word 'inline'
then I compile them into assemble
g++ -S a1.cpp
g++ -S a2.cpp
the result is: inline does not work. function call remained in main.
then I compile them with optimizer
g++ -O2 -S a1.cpp
g++ -O2 -S a2.cpp
the result is : inline works in a2.s, but a1.s also replace the function call. it seems inline was added automatically.
so when inline is necessary when coding.
All the inline keyword does is allow a variable or function to be defined in multiple translation units without violating the One Definition Rule so long as all of the definitions are identical. It has absolutely nothing to do with inlining calls to a function. What it does is allow a function (or variable, since C++17) to be defined inline in a header file that gets included into multiple translation units instead of having to declare the function in the header and define it externally in exactly one translation unit.
Consider the following program:
header.hpp
#include <iostream>
void foo() {
std::cout << "hello world\n";
}
a.cpp
#include "header.hpp"
b.cpp
#include "header.hpp"
int main() {}
This program violates the One Definition Rule because foo is defined in two translation units. Its is thus ill-formed, no diagnostic required. Add the inline keyword to foo and this program will become correct and well defined. foo will still be defined in multiple translation units, but since it's inline and those definitions are identical, the One Definition Rule is not violated.
Note that defining a function in a header like this may aid the compiler in inlining calls to the function (since the function's definition is visible at the point of the call in multiple translation units). It's in no way required though. Most modern compiler/linker toolchains implement some form of link-time optimization that can inline calls to functions defined in other translation units.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With