简体   繁体   中英

Inline all methods in C++, No Cpp file?

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?

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.

No, this is not true. Your main function cannot be inline by definition. See this link for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM