这个问题在这里已有答案:
-
C++ Shared Library with Templates: Undefined symbols error 4个答案
-
Why can templates only be implemented in the header file? 14个答案
我正在尝试为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 step 2:gcc test .c-Wall -L . -la -o c.test gcc test.c -Wall -L . -la -o 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) /tmp/ccldImS1.o:(.data.rel.ro._ZTV3numIiE[_ZTV3numIiE] 0x18):未定义引用num <int> :: show()collect2:错误:ld返回1退出状态Makefile:14:目标配方'cpp.test'失败了make:*** [cpp.test]错误1
我该怎么做才能解决这个问题?