某些"未定义的参考错误"问题已经发布在StackOverflow上,但我无法找到解决问题的方法。
我的项目包含5个文件:5.cpp vector_base.h vector_base.cpp vector.h vector.cpp
我用以下代码编译它:
g++ -std=c++11 vector_base.cpp vector.cpp 5.cpp -o 5
并收到以下错误:
/tmp/ccO8NeGJ.o: In function `main':
5.cpp:(.text.startup+0x21): undefined reference to `Vector<int, std::allocator<int> >::Vector(unsigned int, int const&, std::allocator<int> const&)'
5.cpp:(.text.startup+0x2b): undefined reference to `Vector<int, std::allocator<int> >::destroy_elements()'
collect2: error: ld returned 1 exit status
好吧,代码对我来说很好。我在哪里陷入困境?
代码如下:
5.cpp
#include "vector.h"
int main() {
Vector<int> a{10, 0};
}
vector.h
#ifndef VECTOR_H
#define VECTOR_H
#include "vector_base.h"
template<class T, class A = std::allocator<T>>
class Vector {
private:
vector_base<T,A> vb;
void destroy_elements();
public:
using size_type = unsigned int;
explicit Vector(size_type n, const T& val = T(), const A& a = A());
~Vector() { destroy_elements(); }
};
#endif //VECTOR_H
vector.cpp
#include "vector.h"
#include <algorithm>
#include <memory>
template<class T, class A>
Vector<T,A>::Vector(size_type n, const T& val, const A& a)
:vb{a, n}
{
std::uninitialized_fill(vb.elem, vb.elem + n, val);
}
template<class T, class A>
void Vector<T,A>::destroy_elements()
{
for(T* p = vb.elem; p!=vb.space; ++p){
p->~T();
}
vb.space=vb.elem;
}
vector_base.h
#ifndef VECTOR_BASE_H
#define VECTOR_BASE_H
#include <memory>
template<class T, class A = std::allocator<T>>
struct vector_base {
T* elem;
T* space;
T* last;
A alloc;
using size_type = unsigned int;
vector_base(const A& a, typename A::size_type n)
:alloc{a}, elem{alloc.allocate(n)}, space{elem+n}, last{elem+n} {}
~vector_base() { alloc.deallocate(elem, last-elem); }
};
#endif //VECTOR_BASE_H
vector_base.cpp
#include "vector_base.h"
#include <algorithm>
template<class T, class A>
vector_base<T,A>::vector_base(const vector_base&& a)
:alloc{a.alloc}, elem{a.elem}, space{a.space}, last{a.last}
{
a.elem = a.space = a.last = nullptr;
}
template<class T, class A>
vector_base<T,A>& vector_base<T,A>::operator=(const vector_base&& a)
{
swap(*this, a);
return *this;
}
我尝试分别编译每个cpp文件,然后链接所有文件,但它也没有工作。