C ++ Linking with methods defined in a class definition

For curiosity, if you put the method definition inside the class definition in the header, and the compiler does not embed it, then which object file or files are used to access during the linker phase? Is it placed in every .obj file that includes the header, and then extra copies are removed during the linker phase?

+4
source share
3 answers

If the compiler rejects the embedding of some member function that is defined in a line in the class body or defined as an inline function outside the class body, the compiler inserts the compiled version of the function into each .obj file that uses this function. Note that this is different from inserting a compiled version of each function declared in the header. This file should call this (presumably) inline function.

And yes, the linker will delete duplicate entries. Symbols generated in the symbol table for these built-in functions are weakly coupled. Compare with functions that are not built-in: they have a normal connection, and if one of them is replicated, you have undefined behavior. The typical answer is that the linker complains and then dies.

+1
source

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

In general, yes. See this document.

+4
source

It depends on the compiler, but at least GCC will try to put it in the same object file as the first non-unit member. If all members are inline, then each object file that requires this function (not necessarily all files containing the class definition) will have a copy, and additional copies will be deleted during linking.

+3
source

All Articles