简体   繁体   中英

Inline functions and variables have same address?

I am reading about the inline specifier and I do not really get this part:

3) An inline function or variable (since C++17) with external linkage (eg not declared static) has the following additional properties: 1) It must be declared inline in every translation unit. 2) It has the same address in every translation unit.

What does it mean that functions have the same address, I did not even know that functions had a memory address? And does this also mean that inline variables all have the same addresses, just as if it was one variable? If so, why even use inline on variables?

What does it mean that functions have the same address?

Exactly what it says. Every same inline function in every translation unit has the same address, ie it is only one same function. Why this is important you'll see.

And does this also mean that inline variables all have the same addresses, just as if it was one variable?

Exactly.

If so, why even use inline on variables?

It's like asking why use inline functions. You use inline functions for functions defined in header files, because they are going to be included multiple times in multiple translation units. If they were not inline, the linker will see multiple definitions of the same exact function, and it will complain about duplicate symbols. It doesn't know that the functions are actually the exact same function.

inline comes in here. By marking a function inline , you tell the compiler that it is always the same function, even across multiple translation units. The same thing goes for variables which are defined in header files. They too are included in multiple translation units, and the linker doesn't know that they should refer to the same exact variable. inline fixes this once again.

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