Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do inline functions have addresses?

Tags:

c++

inline

In section 7.1.1 of the book "The C++ Programming Language" the author states:

"inline function still has a unique address and so do the static variables of an inline function"

I am confused. If I have an inline function then it can't have address. Does this happen in C also?

like image 958
Xolve Avatar asked Jul 23 '10 12:07

Xolve


People also ask

How does inline function actually work?

An inline function is one for which the compiler copies the code from the function definition directly into the code of the calling function rather than creating a separate set of instructions in memory. This eliminates call-linkage overhead and can expose significant optimization opportunities.

What is difference between inline function and non inline function?

Functions that are present inside a class are implicitly inline. Functions that are present outside class are considered normal functions.

Can inline functions have static variables?

Static local variables are not allowed to be defined within the body of an inline function. C++ functions implemented inside of a class declaration are automatically defined inline.


2 Answers

The inline attribute is just a hint to the compiler that it should try to inline your function. It's still possible to take the address of the function, and in that case the compiler will also need to emit a non-inline version.

For example:

#include <stdio.h>

inline void f() {
    printf("hello\n");
}

int main() {
    f();
    void (*g)() = f;
    g();
}

The above code prints hello twice.

My gcc compiler (with -O) emits code something like this:

_main:
        pushl   %ebp
        movl    %esp, %ebp
        pushl   %ebx
        subl    $20, %esp
        call    ___i686.get_pc_thunk.bx
"L00000000002$pb":
        leal    LC0-"L00000000002$pb"(%ebx), %eax
        movl    %eax, (%esp)
        call    L_puts$stub        ; inlined call to f()
        call    L__Z1fv$stub       ; function pointer call to f() (g is optimised away)
        movl    $0, %eax
        addl    $20, %esp
        popl    %ebx
        popl    %ebp
        ret

As you can see, there is first a call to puts() and then a call to L__Z1fv() (which is the mangled name of f()).

like image 133
Greg Hewgill Avatar answered Oct 17 '22 22:10

Greg Hewgill


Inline functions are have addresses if you need one. Standard only says that:

An inline function with external linkage shall have the same address in all translation units.

like image 6
Kirill V. Lyadvinsky Avatar answered Oct 17 '22 23:10

Kirill V. Lyadvinsky