What Does It Mean For a C++ Function To Be Inline?

后端 未结 9 774
攒了一身酷
攒了一身酷 2020-12-01 06:12

See title: what does it mean for a C++ function to be inline?

9条回答
  •  抹茶落季
    2020-12-01 07:03

    As well as the other (perfectly correct) answers about the performance implications of inline, in C++ you should also note this allows you to safely put a function in a header:

    // my_thing.h
    inline int do_my_thing(int a, int b) { return a + b; }
    
    // use_my_thing.cpp
    #include "my_thing.h"
    ...
        set_do_thing(&do_my_thing);
    
    // use_my_thing_again.cpp
    ...
        set_other_do_thing(&do_my_thing);
    

    This is because the compiler only includes the actual body of the function in the first object file that needs a regular callable function to be compiled (normally because it's address was taken, as I showed above).

    Without the inline keyword, most compilers would give an error about multiple definition, eg for MSVC:

    use_my_thing_again.obj : error LNK2005: "int __cdecl do_my_thing(int,int)" (?do_my_thing@@YAHHH@Z) already defined in use_my_thing.obj
    <...>\Scratch.exe : fatal error LNK1169: one or more multiply defined symbols found
    

提交回复
热议问题