如何使用模板类在Linux中构建动态库(.so)

时间:2018-07-15 14:13:42

标签: c++ linux shared-libraries dynamic-linking

我试图为gcc和g ++创建一个库。
我在那里使用了用于c ++的模板类。运行make命令后, 库liba.so已成功编译。
然后编译了test.c,也成功编译了。
在第3步,test.cpp的编译失败,并显示了一些未定义的参考错误。

Makefile

CPP=g++
CC=gcc
FLAGS=-Wall -L. -la
LIBFLAGS=-fPIC -shared -Wl,-soname,liba.so -o liba.so
.PHONY: all
all: liba.so c.test cpp.test
liba.so:
    @echo "step 1:${CPP} ${FLAGS} ${LIBFLAGS} lib.cpp"
    ${CPP} ${LIBFLAGS} lib.cpp
c.test: liba.so
    @echo "step 2:${CC} test.c${FLAGS} -o c.test"
    ${CC} test.c ${FLAGS} -o c.test
cpp.test: liba.so
    @echo "step 3:${CPP} test.cpp ${FLAGS} -o cpp.test"
    ${CPP} test.cpp ${FLAGS} -o cpp.test

lib.h

#ifndef __LIB_H__
#define __LIB_H__
#ifdef __cplusplus
template <class T>
class num
{
    private:
    T a;
    public:
        virtual void operator=(T arg);
        virtual void show();
};
#endif
#ifdef __cplusplus
extern "C" {
#endif
    void sint(int a);
#ifdef __cplusplus
}
#endif
#endif

lib.cpp

#include <stdio.h>
#include <iostream>
#include "lib.h"
extern "C" {
    void sint(int a)
    {
        printf("%d\n",a);
    }
}
extern "C++" {
    template <class T> void num<T>::operator=(T arg)
    {
        this->a=arg;
    }
    template <class T>void num<T>::show()
    {
        std::cout<<this->a<<std::endl;
    }
}

test.c

#include<stdio.h>
#include "lib.h"
int main()
{
    sint(55);
    return 0;
}

test.cpp

#include<iostream>
#include "lib.h"
using namespace std;
int main()
{
    num<int> a;
    a=5;
    a.show();
    return 0;
}

进行输出

  

步骤1:g ++ -Wall -L。 -la -fPIC -shared -Wl,-soname,liba.so -o liba.so   lib.cpp g ++ -fPIC -shared -Wl,-soname,liba.so -o liba.so lib.cpp

     

第2步:gcc test.c-Wall -L。 -la -o c.test gcc test.c -Wall -L。啦啦   c.test

     

第3步:g ++ test.cpp -Wall -L。 -la -o cpp.test g ++ test.cpp -Wall -L。   -la -o cpp.test

     

/tmp/ccldImS1.o:在函数main中:
test.cpp :(。text + 0x26):对num<int>::operator=(int)的未定义引用
test.cpp :( .text + 0x43):未定义对num<int>::show()的引用
/tmp/ccldImS1.o:(.data.rel.ro._ZTV3numIiE[_ZTV3numIiE]+0x10):未定义对num<int>::operator=(int)的引用< br /> /tmp/ccldImS1.o:(.data.rel.ro._ZTV3numIiE[_ZTV3numIiE]+0x18):未定义对num<int>::show()的引用
collect2:错误:ld返回1退出状态
Makefile:14:目标“ cpp.test”的配方失败
make:*** [cpp.test]错误1

该怎么办?

0 个答案:

没有答案