To make a function inline should I add the keyword inline in function prototype or in function definition or should I add the inline keyword both in function declaration and function definition.
2 Answers
If you already have a declaration and definition, you don't need to add inline anywhere. The inline keyword is not a magical optimization incantation, but more of a linkage specifier.
An inline function must be defined in every translation unit it's used in. How can it be defined there? Simple, it's put in header:
// foo.h inline void foo() {} But wait, I hear you say, won't putting it in header cause a multiple definitions error? Not when it's marked inline, that's why I called it more of a linkage specifier. The inline specifier tells the compiler that all those multiple definition it sees are the same. So it may in fact use any one of them. Or it may inspect the function body and choose to do code inlining, but it doesn't have to.
The primary purpose of the keyword is to allow those multiple definitions to appear inline, not to cause the function's code to be inlined. So again, if you have a definition in a cpp file and a declaration in a header, you don't need to do anything. If you have a utility you want to appear in a header, put it there - definition and all - and add the inline keyword.
Comments
How to make function inline:
To make any function as inline, start its definitions with the keyword “inline”.
From the article.
inlinekeyword is only a hint. The compiler is free to disregard it. And it's also free to compile functions not marked withinlineas inline.inlinekeyword or not. A definition (implementation) of the function is needed to be able to inline it.inlinekeyword to inline functions with a modern compiler? or should we let the compiler decide for us most of the time?inline, even if you don't add the keyword.