この合成例を考えてみましょう。Visual Studio 2010 ソリューションに 2 つのネイティブ C++ プロジェクトがあります。1 つはコンソール exe で、もう 1 つは lib です。
lib には 2 つのファイルがあります。
// TImage.h
template<class T> class TImage
{
public:
TImage()
{
#ifndef _LIB
std::cout << "Created (main), ";
#else
std::cout << "Created (lib), ";
#endif
std::cout << sizeof(TImage<T>) << std::endl;
}
#ifdef _LIB
T c[10];
#endif
};
void CreateImageChar();
void CreateImageInt();
と
// TImage.cpp
void CreateImageChar()
{
TImage<char> image;
std::cout << sizeof(TImage<char>) << std::endl;
}
void CreateImageInt()
{
TImage<int> image;
std::cout << sizeof(TImage<int>) << std::endl;
}
そしてexeの1つのファイル:
// main.cpp
int _tmain(int argc, _TCHAR* argv[])
{
TImage<char> image;
std::cout << sizeof(TImage<char>) << std::endl;
CreateImageChar();
CreateImageInt();
return 0;
}
私は実際にこのようにするべきではありませんが、これは何が起こっているのかを理解するためのものです. そして、それは、何が起こるかです:
// cout:
Created (main), 1
1
Created (main), 1
10
Created (lib), 40
40
リンカは lib のバージョンのTImage<char>
を exe のバージョンの でオーバーライドしTImage<char>
ます。しかし、exe のバージョンの がないためTImage<int>
、lib のバージョンのTImage<int>
?.. が保持されます。
更新:以下の効果の説明は正しいです、ありがとう。しかし、問題は「これがどのように起こったのか」でした.. 「複数定義されたシンボル」のようなリンカーエラーが発生することを期待していました。したがって、最も適切な回答はAntonio Pérez の回答からのものです。