Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can modern C++ compilers inline functions that are defined in a cpp file

Tags:

I am aware that the keyword inline has useful properties e.g. for keeping template specializations inside a header file. On the other hand I have often read that inline is almost useless as hint for the compiler to actually inline functions. Further the keyword cannot be used inside a cpp file since the compiler wants to inspect functions marked with the inline keyword whenever they are called.

Hence I am a little confused about the "automatic" inlining capabilities of modern compilers (namely gcc 4.43). When I define a function inside a cpp, can the compiler inline it anyway if it deems that inlining makes sense for the function or do I rob him of some optimization capabilities ? (Which would be fine for the majority of functions, but important to know for small ones called very often)

like image 326
Martin Avatar asked Dec 09 '11 18:12

Martin


People also ask

Does C support inline functions?

Standard supportC++ and C99, but not its predecessors K&R C and C89, have support for inline functions, though with different semantics. In both cases, inline does not force inlining; the compiler is free to choose not to inline the function at all, or only in some cases.

Can inline function be defined in source file?

For example, an inline function or an inline variable (since C++17) may be defined in a header file that is included in multiple source files.

Do compilers automatically inline functions?

Automatic function inlining and static functions At -O2 and -O3 levels of optimization, or when --autoinline is specified, the compiler can automatically inline functions if it is practical and possible to do so, even if the functions are not declared as __inline or inline .

What are inline member functions in C++?

A member function that is defined inside its class member list is called an inline member function. Member functions containing a few lines of code are usually declared inline. In the above example, add() is an inline member function.


1 Answers

Within the compilation unit the compiler will have no problem inline functions (even if they are not marked as inline). Across compilation units it is harder but modern compilers can do it.

Use of the inline tag has little affect on 'modern' compilers and whether it actually inlines functions (it has better heuristics than the human mind) (unless you specify flags to force it one way or the other (which is usually a bad idea as humans are bad at making this decision)).

like image 54
Martin York Avatar answered Sep 20 '22 22:09

Martin York