Quantcast
Channel: The Old New Thing
Viewing all articles
Browse latest Browse all 24428

re: Understanding the classical model for linking, groundwork: The algorithm

$
0
0

@Matt:

The thing that made selectany necessary I suspect was templates. (I'm familiar with a mechanism of similar description to selectany but am not familiar enough with MSVC specifically to know if that's what the exact mechanism it uses in the following situation.) Basically the only way that templates work (ignoring 'export' which almost no one supports anyway) is by putting the template definitions in headers. Each compilation unit in which the template is instantiated will have the symbols. If I have foo.cpp with a call to 'vector<int>::push_back(int)' and bar.cpp with a call to 'vector<int>::push_back(int)', then the compiler will instantiate that function in both compilation units, generating code in both. Under the classical model, at link time: poof, duplicate definition.*

There are other places it gets used -- in particular, functions defined in headers (e.g. because you want them inlined) -- but templates are what basically forced the linker's hand and left little choice.

* The reason that this is basically how templates *have* to work is the following. Let's suppose you are defining some 'template<typename T> class MyVector' in MyVector.cpp, and instantiating it with 'MyVector<string>' and 'MyVector<int>' in Stuff.cpp. (There would be a non-defining declaration in MyVector.hpp that's included from Stuff.cpp.) The compiler never knows what it needs to do! When compiling 'MyVector.cpp' it knows what the C++ code for the MyVector template is, but it doesn't know what types it must instantiate it with. (Each instantiation gets separate generated code.) When compiling 'Stuff.cpp' it knows what types 'MyVector' has been instantiated with, but it doesn't know what the C++ code is and so can't do the instantiation! The only resolutions are (1) to require that the C++ code and instantiations are co-located (which is usually done by putting the definitions of the template into the header file), or (2) to have the compiler produce a list of instantiations which should be done at link time. The latter puts a lot of burden on the linker and will make links take potentially a long time.


Viewing all articles
Browse latest Browse all 24428

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>