关于命名空间类编译成库后调用的不解.高手解答下... undefined reference to
AAA.h
#ifndef __AAA__
#define __AAA__
namespace aaa
{
template<typename T>
class AAA
{
public:
AAA();
~AAA();
T Sum(T a, T b);
};
}
#endif
AAA.cpp
#include "AAA.h"
template<typename T>
aaa::AAA<T>::AAA()
{
}
template<typename T>
aaa::AAA<T>::~AAA()
{
}
template<typename T>
T aaa::AAA<T>::Sum(T a, T b)
{
return a + b;
}
g++ -g -D_REENTRANT -Wall -I/home/yanghao/c++/MQ1/include -c AAA.cpp -o AAA.o
ar rv libAAA.a AAA.o
r - AAA.o
ranlib libAAA.a
编译成库 libAAA.a
把AAA.h 与 libAAA.a cp 到另外一个地方
用 test.cpp 引用库
test.cpp
#include <string>
#include <iostream>
#include "AAA.h"
using namespace aaa;
int main()
{
AAA<int> ax;
std::cout<<ax.Sum(1, 2)<<std::endl;
return 0;
}
编译:
g++ -g -D_REENTRANT -Wall -lgcc_s -I/home/yanghao/c++/MQ2/include -c test.cpp -o test.o
g++32: -lgcc_s: linker input file unused because linking not done
g++ -o test -g -D_REENTRANT -Wall -lgcc_s test.o -L/usr/lib -L/home/yanghao/c++/MQ2/lib -lpthread -ldl -lAAA
test.o(.text+0x19): In function `main':
/home/yanghao/c++/MQ2/source/test.cpp:7: undefined reference to `aaa::AAA<int>::AAA()'
test.o(.text+0x2f):/home/yanghao/c++/MQ2/source/test.cpp:9: undefined reference to `aaa::AAA<int>::Sum(int, int)'
test.o(.text+0x54):/home/yanghao/c++/MQ2/source/test.cpp:9: undefined reference to `aaa::AAA<int>::~AAA()'
test.o(.text+0x71):/home/yanghao/c++/MQ2/source/test.cpp:9: undefined reference to `aaa::AAA<int>::~AAA()'
collect2: ld returned 1 exit status
但是在如果把AAA 的模板去掉 编译成库后,再拿到test里来编译 就没问题了,
不解 不知道这是个什么情况?