3 ms·
Function definitions in headers are compiled and included in the object file, then all but one copy is discarded during linking. Reading and discarding all this
by tlb 3y ago
Function definitions in headers are compiled and included in the object file, then all but one copy is discarded during linking. Reading and discarding all this stuff adds some time to the linking process, which is a noticeable fraction of total build time if you're only recompiling one source file.
- JonChesterfield 3y agoModerately interesting that the compile-N-times-keep-one is a C++ thing. C's inline makes you specify which translation unit exports the symbol so the compiler knows whether it is working with the canonical symbol or one that it can discard at will. Thus it can inline functions, but if it chooses not to, it doesn't have to optimise&codegen that function just to have the linker probably throw it away.
- kimixa 3y agoYou can do the same for c++ with extern templates, just instantiate them with the needed types in one compilation unit and you only end up with a single set of symbols, and codegen etc. only runs the once. And C inline functions are instantiated and generated for every compilation unit that uses it - it just doesn't generate exported symbols in the resulting object file. Exactly the same as the "inline" keyword in c++.
- astrobe_ 3y agoDeclarations, not definitions. Declarations go into object files as symbol names for the purpose of linking. You can have multiple declarations as long as they are the same (or if they are not they define different things in C++ due to overloading), but you cannot have multiple definitions (even in different object files) even if they are identical (compiler doesn't bother checking they are, it sees it as fishy and just drops a "multiple definitions" error).
- tlb 3y agoNo, C++ header files contain definitions too, which are emitted into every object file where they're used. If it's something allowed to be multiply defined it's emitted as a "weak" symbol, and the linker eliminates duplicates. This includes every inline function that's used, and many default-generated functions, such as default constructors & destructors and virtual function tables. For a simple example, See https://godbolt.org/z/qhvaP8Eed https://godbolt.org/z/qhvaP8Eed and observe the Foo::Foo() constructor, which would be emitted in every .o file with the 'struct Foo' definition.
- astrobe_ 3y agoOk, thanks for the correction.