Makefile设置导致vtable错误

时间:2013-11-24 03:56:44

标签: c++ makefile

我正在尝试制作一个简单的程序,我使用模板和继承。 我正在使用Linux gcc。但是,在eclipse cdt中,如果我只给出自己的makefile,我会得到关于vtable undefined reference的错误。另一方面,如果我检查构建中的选项,即自动生成makefile ,则错误消失。有人可以指出可能出现的问题吗?

这是我的带有header和makefile的类

AbstractVehicleFactory.h:

class AbstractVehicleFactory {
public:
    AbstractVehicleFactory() {}
    virtual ~AbstractVehicleFactory() {}
    IVehicle* getVehicle();

    virtual IVehicle* createVehicle() = 0;
private:
    IVehicle* mVehicle;
};

AbstractVehicleFactory.cpp

IVehicle* AbstractVehicleFactory::getVehicle() {
    if(!mVehicle) {
        mVehicle = createVehicle();
    }
    return mVehicle;
}

StandardVehicle.h:

#include "AbstractVehicleFactory.h"
template<typename T>
class StandardVehicle: public AbstractVehicleFactory {
public:
    StandardVehicle();
    virtual ~StandardVehicle();
protected :
    IVehicle* createVehicle();
private:
    T* mVehicle;
};

StandardVehicle.cpp:

template<typename T>
StandardVehicle<T>::StandardVehicle() {
    mVehicle = 0;
}

template<typename T>
StandardVehicle<T>::~StandardVehicle() {
}

template<typename T>
IVehicle* StandardVehicle<T>::createVehicle() {
    return new T();
}

Makefile:

# compiler
CXX = g++

CXXFLAGS = -O2 -g -Wall -fmessage-length=0

SOURCES= $(wildcard *.cpp)

OBJECTS= $(SOURCES:.cpp=.o)

TARGET= Vehicle.exe

$(TARGET): $(OBJECTS) 
        $(CXX) -o $(TARGET) $(OBJECTS) $(LIBS) $(LDFLAGS)

all:  $(SOURCES) $(TARGET) 



clean:
    rm -f $(OBJECTS) $(TARGET)

Error:

g++ -o Vehicle.exe AbstractVehicleFactory.o Bus.o FactoryPattern.o IVehicle.o StandardVehicle.o  
AbstractVehicleFactory.o:(.rodata._ZTV22AbstractVehicleFactory[vtable for AbstractVehicleFactory]+0x10): undefined reference to `AbstractVehicleFactory::createVehicle()'
collect2: ld returned 1 exit status
make: *** [Vehicle.exe] Error 1

有人可以指出可能出错的地方吗?

编辑:即使在检查makefile自动生成后,我也会将StandardVehicle构造函数的错误视为未定义的引用。 StandardVehicle.o也不显示任何组件。它建造得不好吗?

1 个答案:

答案 0 :(得分:1)

您的代码说:

public:
StandardVehicle() ;

你不能这样做,因为它是一个模板。你必须在.h

中有身体

稍后在另一个cpp文件中使用模板时,如下所示:

StandardVehicle<int>   myvar ;

编译器会立即在那里制作StandardVehicle<int>的所有代码,因此它不能引用StandardVehicle.cpp中的代码