Inline function prototype vs regular declaration v

2019-01-28 09:54发布

问题:

What's the difference between inline function and then main like so:

inline double cube(double side)
{
   return side * side * side;
}

int main( )
{
    cube(5);
}

vs just declaring a function regularly like:

double cube(double side)
{
   return side * side * side;
}

int main( )
{
    cube(5);
}

vs function prototype?

double cube(double);

int main( )
{
    cube(5);
}

double cube(double side)
{
   return side * side * side;
}

回答1:

An inline function can be defined in multiple translation units (cpp file + includes), and is a hint to the compiler to inline the function. It is usually placed in a header which increases compile time, but can lead to faster code. It also allows the function to be used from many compilation units.

//cube.h
inline double cube(double side)
{
   return side * side * side;
}

//cube.cpp
int main( )
{
    cube(5);
}

Defining it regularly is the normal method, where it's (usually) defined in a cpp file, and linked against. It is not easily used from other compilation units.

//cube.cpp
double cube(double side)
{
   return side * side * side;
}

int main( )
{
    cube(5);
}

A prototype allows you to tell the compiler that a function will exist at link time, even if it doesn't exist quite yet. This allows main to call the function, even though it doesn't exist yet. Commonly, prototypes are in headers, so other compilation units can call the function, without defining it themselves. This has the fastest compilation time, and the function is easily used from other compilation units.

//cube.h
double cube(double);

//cube.cpp
int main( )
{
    cube(5);
}

double cube(double side)
{
   return side * side * side;
}


回答2:

Performance wise, they are all the same since inline is just a hint for the compiler. If the separation of declaration/definition is used and the definition is on a different translation unit, then it will be harder for the compiler to inline it (but there are implementations that do so).

A difference with making a function inline or not is that the linker will not complain if it sees the same inline definition for a function more than once.



回答3:

The 3 program compile to exactly the same with g++ -S -O3 $file.cc. Except for the second example where the definition of double cube(double side) still exist in a non inlined form though inlined in int main().

_main:
pushl   %ebp
movl    $16, %eax
movl    %esp, %ebp
subl    $8, %esp
andl    $-16, %esp
call    __alloca
call    ___main
leave
xorl    %eax, %eax
ret


回答4:

When you declare a function inline the compiler tries to speed up the code by more or less copying the body of the function to where it's called. It's only a suggestion and it's up the the compiler to make the decision on if it's possible.

I'm not sure what would happen in the 3rd example. I imagine it would depend on the tool chain being used.