問題描述
我正在嘗試使用模板類鏈接到共享庫,但它給了我未定義符號"錯(cuò)誤.我已將問題濃縮為大約 20 行代碼.
I'm trying to link to a shared library with a template class, but it is giving me "undefined symbols" errors. I've condensed the problem to about 20 lines of code.
shared.h
template <class Type> class myclass {
Type x;
public:
myclass() { x=0; }
void setx(Type y);
Type getx();
};
shared.cpp
#include "shared.h"
template <class Type> void myclass<Type>::setx(Type y) { x = y; }
template <class Type> Type myclass<Type>::getx() { return x; }
ma??in.cpp
#include <iostream>
#include "shared.h"
using namespace std;
int main(int argc, char *argv[]) {
myclass<int> m;
cout << m.getx() << endl;
m.setx(10);
cout << m.getx() << endl;
return 0;
}
這是我編譯庫的方式:
g++ -fPIC -c shared.cpp -o shared.o
g++ -dynamiclib -Wl,-dylib_install_name -Wl,libshared.dylib -o libshared.dylib shared.o
和主程序:
g++ -c main.cpp
g++ -o main main.o -L. -lshared
只得到以下錯(cuò)誤:
Undefined symbols:
"myclass<int>::getx()", referenced from:
_main in main.o
_main in main.o
"myclass<int>::setx(int)", referenced from:
_main in main.o
如果我刪除 shared.h/cpp
中的模板"內(nèi)容,并將它們替換為int",則一切正常.此外,如果我只是將模板類代碼直接復(fù)制并粘貼到 main.cpp
中,并且不鏈接到共享庫,則一切正常.
If I remove the 'template' stuff in shared.h/cpp
, and replace them with just 'int', everything works fine. Also, if I just copy&paste the template class code right into main.cpp
, and don't link to the shared library, everything works as well.
如何讓這樣的模板類通過共享庫工作?
How can I get a template class like this to work through a shared library?
我使用的是 MacOS 10.5 和 GCC 4.0.1.
I'm using MacOS 10.5 with GCC 4.0.1.
推薦答案
除了其他答案之外,您還可以顯式實(shí)例化模板類.這僅在您事先知道模板參數(shù)可能采用的類型時(shí)才有用.您使用庫中的所有這些類型實(shí)例化模板.
In addition to the other answers, you can explicitly instantiate template classes. This is only useful if you know beforehand what types the template parameters may assume. You instantiate the template with all these types in the library.
為了編譯您的示例,只需將以下內(nèi)容添加到 shared.cpp 的末尾:
For your example to compile, just add the following to the end of shared.cpp:
// Instantiate myclass for the supported template type parameters
template class myclass<int>;
template class myclass<long>;
這會使用 Type=int 實(shí)例化模板并將實(shí)例化的代碼放在共享庫中.根據(jù)需要為所有類型添加盡可能多的顯式實(shí)例.
This instantiates the template with Type=int and places the instantiated code in the shared library. Add as many explicit instantiations as you need, for all the types you need.
同樣,如果您希望能夠使用任意類型參數(shù)實(shí)例化模板,那么您必須將定義添加到頭文件中,以便編譯器知道模板的源代碼在其他編譯單元中實(shí)例化時(shí).
Again, if you want to be able to instantiate the template with any arbitrary Type parameter, then you must add the definitions to the header file, so that the compiler knows the source code of the template when instantiating it in other compilation units.
這篇關(guān)于帶有模板的 C++ 共享庫:未定義符號錯(cuò)誤的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!