Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extern inline functions must have the same address in all translation units. How the heck is that achieved?

Tags:

c++

inline

According to the standard, extern inline functions must the same address in all translation units.

How is this achieved in the compiler? I mean when I'm compiling some translation unit, I have no idea what the other TU will be like. So how can I have the same address everywhere?

like image 860
Šimon Tóth Avatar asked Oct 18 '11 10:10

Šimon Tóth


People also ask

Can inline functions extern?

Similarly, if you define a function as extern inline , or redeclare an inline function as extern , the function simply becomes a regular, external function and is not inlined. End of C only. Beginning of C++ only.

What is extern inline?

- "static inline" means "we have to have this function, if you use it but don't inline it, then make a static version of it in this compilation unit" - "extern inline" means "I actually _have_ an extern for this function, but if you want to inline it, here's the inline-version" ... we should just convert all current ...

How do you define an inline function outside class?

An equivalent way to declare an inline member function is to either declare it in the class with the inline keyword (and define the function outside of its class) or to define it outside of the class declaration using the inline keyword.

What is inline function What are their advantages give an example?

Inline functions provide following advantages: 1) Function call overhead doesn't occur. 2) It also saves the overhead of push/pop variables on the stack when function is called. 3) It also saves overhead of a return call from a function.


2 Answers

That's up to the implementation, but usually it's resolved by the linker. Each compiled translation unit will produce an object file containing a copy of the function, flagged in some way so that the linker knows that it should expect (and accept) duplicates. The linker will include one of them, discard the others, and resolve any references to the function.

like image 186
Mike Seymour Avatar answered Sep 28 '22 01:09

Mike Seymour


Simple strategy: every time such an inline function is defined, compile it to object time as if it were a normal function. Then, at link time, detect duplicate functions and remove them, leaving one copy of each. This is how C++ compilers used to work (also in the face of templates) some 10 years ago. Not sure how they do it nowadays.

like image 42
Fred Foo Avatar answered Sep 28 '22 01:09

Fred Foo