0

阅读以下对模板函数的未定义引用我解决了我的问题,但是我的模板函数实际上是在库中被调用的,所以它正在实现我原以为这应该在共享对象中定义了它的类型,但是我一直在获取链接器错误。考虑...

我在下面定义了以下文件(common.h、common.cpp、myclass.h 和 myclass.cpp):

常见的.h

namespace myn
{
    template<class T> T map(T val1, T val2);
};

常见的.cpp

#include "common.h"
template<class T> T myn::map(T val1, T val2)
{
    return val1+val2;
}

我的班级.h

#include "common.h"
class myclass
{
private:
    int val;
public:
    myclass(int v1, int v2);
};

我的类.cpp

#include "myclass.h"
myclass::myclass(int v1, int v2)
{
    this->val = myn::map<int>(v1, v2);
}

我使用以下方法编译库:

g++ -Wall -fPIC -c common.cpp -o common.o
g++ -Wall -fPIC -c myclass.cpp -o myclass.o
g++ -shared -Wl,-soname,libmylib.so -o libmylib.so common.o myclass.o

给出时main.cpp

#include "common.h"
#include "myclass.h"

int main(int argc, char ** argv)
{
    myclass * x = 0;

    if (argc == 1)
        x = new myclass(20, 40);
    else
        x = new myclass(2343, 435);

    delete x;
    return 0;
}

我编译使用:

g++ -Wall -L. main.cpp -o main.out -lmylib

我收到以下错误:

./libmylib.so: undefined reference to `int myn::map<int>(int, int)'
collect2: error: ld returned 1 exit status

不应该定义函数的<int>版本吗?map我知道如果我尝试做类似myn::map<char>('a', 'b');它应该抱怨的事情,因为它没有被定义,但在我的案例中,<int>模板肯定是定义的。

4

0 回答 0