简体   繁体   中英

What is an 'extern inline' function and when to use?

There is such thing and it's in the latest C++ draft:

At § 7.1.2 .4:

An inline function shall be defined in every translation unit in which it is odr-used and shall have exactly the same definition in every case (3.2). [ Note: A call to the inline function may be encountered before its definition appears in the translation unit. — end note ] If the definition of a function appears in a translation unit before its first declaration as inline, the program is ill-formed. If a function with external linkage is declared inline in one translation unit, it shall be declared inline in all translation units in which it appears; no diagnostic is required. An inline function with external linkage shall have the same address in all translation units. A static local variable in an extern inline function always refers to the same object. A type defined within the body of an extern inline function is the same type in every translation unit.

Some insights on what is this and when to use it?

extern is redundant for functions, so it is pointless to declare a function extern inline . If, for example you declared a function inline at global scope, the rules of this section would apply. Likewise if you declared a class at global scope and defined a member function within the class definition, as such a function would be implicitly inline .

The question of when you should declare a function inline is a can of worms I'm not inclined to open here. See: When should I write the keyword 'inline' for a function/method?

I am not familiar with this draft feature in C++, and whether it made it into a standard. I think it may be borrowing a feature from C.


In C (I think C99?), extern inline is used in a source file, not a header file. to instruct the tooling that the object file produced from this source should be the one that holds the final implementation. Without it, the linker has to choose a site or duplicate the symbol.

For example, in my_alloc.h :

inline char *my_alloc(size_t len) { return (char*)malloc(len); }

And in my_alloc.c :

extern inline char *my_alloc(size_t len);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM