Reputation: 1625
I want to write an application in C++ with the best runtime performance. So I decided to inline all methods.
I have the problem mentioned here.
It gives me undefined reference error if I use inline keyword inside cpp file in both MSVC 2015 and MinGW compilers.
But if I want to inline all methods inside the header file, there would be no cpp files needed. Is that true? Why is that?
Upvotes: 0
Views: 164
Reputation: 10425
The keyword inline
has nothing to do with performance in this day and age and nothing to do with inlining a function!
In fact it has to do with the One Definition Rule (or ODR)!
The ODR states that a C++ program shall have only one definition of each function.
This means that the following is will produce an error:
file.cpp
void fun() {}
main.cpp
void fun() {}
This is an error, because there are two definitions of the same function in two different translational units (.cpp
files) which is a violation of the ODR.
Now the inline
keyword allows you to get around this. It allows you to define the same function in multiple translational units, as long as the function body is exactly the same! This allows you to define the function in a header file which can then be included into multiple .cpp
files.
That being said. What you described will not cause a performance slowdown. The compiler will inline the correct functions in the appropriate time. It will make your code run faster than you could ever do it yourself.
Upvotes: 3
Reputation: 1329
No, this is not true. Your main function cannot be inline by definition. See this link for more information.
Upvotes: 1