play store
play store

Reputation: 393

How to make a function inline in C++

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.

Upvotes: 1

Views: 602

Answers (2)

Saurabh P Bhandari
Saurabh P Bhandari

Reputation: 6742

How to make function inline:

To make any function as inline, start its definitions with the keyword “inline”.

From the article.

Upvotes: 3

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.

Upvotes: 5

Related Questions