简体   繁体   中英

C++ Linking with Methods Defined in the Class Definition

For curiosity's sake, if you put the method definition inside the class definition in the header, and the compiler doesn't inline it, then what object file or files is that method put into for accessing during the linker phase? Is it put in every.obj file that includes the header, and then extra copies are thrown away during the linker phase?

Is it put in every.obj file that includes the header, and then extra copies are thrown away during the linker phase?

In general, yes. See this paper.

It depends on the compiler, but GCC at least will try to place it in the same object file as the first non-inline member. If all members are inline, then there will be a copy in every object file that requires the function (not necessarily all files that include the class definition), and the extra copies are thrown away during linking.

If the compiler rejects inlining some member function that is defined in-line in the body of the class or is defined as an inline function outside the body of the class, the compiler will insert a compiled version of the function in every.obj file that uses that function. Note that this is different from inserting a compiled version of every function declared in the header. The file in question has to invoke that (supposedly) inline function.

And yes, the linker will delete duplicate entries. The symbols generated in the symbol table for these inlined functions have weak linkage. Compare to functions that aren't inlined: They have normal linkage, and if one of those is replicated you have undefined behavior. The typical response is for the linker to complain and then die.

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