Alex Rivera | Logout

Inline keyword vs header definition

Asked 2012-04-11T09:20:54.390
26

What's the difference between using the inline keyword before a function and just declaring the whole function in the header?

so...

int whatever() { return 4; }

vs

.h:

inline int whatever();

.cpp:

inline int myClass::whatever()
{
    return 4;
}

for that matter, what does this do:

inline int whatever() { return 4; }
Edit
Report

2 Answers

10

without inline, you will likely end up with multiple exported symbols, if the function is declared at the namespace or global scope (results in linker errors).

however, for a class (as seen in your example), most compilers implicitly declare the method as inline (-fno-default-inline will disable that default on GCC).

if you declare a function as inline, the compiler may expect to see its definition in the translation. therefore, you should reserve it for the times the definition is visible.

at a higher level: a definition in the class declaration is frequently visible to more translations. this can result in better optimization, and it can result in increased compile times.

unless hand optimization and fast compiles are both important, it's unusual to use the keyword in a class declaration these days.

answered 2012-04-11T09:25:32.713
10

The purpose of inline is to allow a function to be defined in more than one translation unit, which is necessary for some compilers to be able to inline it wherever it's used. It should be used whenever you define a function in a header file, although you can omit it when defining a template, or a function inside a class definition.

Defining it in a header without inline is a very bad idea; if you include the header from more than one translation unit, then you break the One Definition Rule; your code probably won't link, and may exhibit undefined behaviour if it does.

Declaring it in a header with inline but defining it in a source file is also a very bad idea; the definition must be available in any translation unit that uses it, but by defining it in a source file it is only available in one translation unit. If another source file includes the header and tries to call the function, then your program is invalid.

answered 2012-04-11T10:34:29.543

Your Answer