编译:包括库:未定义引用`vtable for class`

时间:2013-07-07 11:08:27

标签: c++ compilation dynamic-library

我正在尝试使用源文件创建一个库,然后在我的程序中使用该库。但链接器抛出关于vtable的错误:

以下是代码:

product.h
--------------------------------------------------------------
# ifndef PRODUCT_H_
#define PRODUCT_H_

# include <iostream>
# include <string>
using namespace std ;

class Product {
        public:
        virtual ~Product () {}
        virtual string GetProductCode () = 0 ;
} ;
# endif


newproduct.h
--------------------------------------------------------------
# ifndef NEWPRODUCT_H_
#define NEWPRODUCT_H_

# include "product.h"
# include <string>
using namespace std ;

class NewProduct : public Product {
        public:
        NewProduct () {cout<<"Creating New product"<<endl;}
        virtual string GetProductCode () ;
} ;

# endif

newproduct.cc
--------------------------------------------------------------
# include "newproduct.h"

string NewProduct::GetProductCode () {
                return "New Product" ;
}

main.cc
--------------------------------------------------------------
# include "product.h"
# include "newproduct.h"
# include <iostream>

using namespace std;
int main ()
{
        Product * prod = new NewProduct ();
        prod->GetProductCode () ;
        delete prod ;
        return 0;
}

我正在尝试执行以下步骤:

1)export LD_LIBRARY_PATH = $ LD_LIBRARY_PATH:。

2)g ++ -o libprodlib.so newproduct.o -shared

3)g ++ -o demo main.cc -L lprodlib.so

但是这给了我错误:

/tmp/ccqI60q9.o: In function `NewProduct::NewProduct()':
main.cc:(.text._ZN10NewProductC2Ev[_ZN10NewProductC5Ev]+0x17): undefined reference to `vtable for NewProduct'
collect2: ld returned 1 exit status

你能告诉我上面出了什么问题吗?

由于

1 个答案:

答案 0 :(得分:0)

要制作共享的.so文件,您可以这样做:

$g++ -shared -fPIC newproduct.cc -o libprodlib.so
$g++ main.cc -o daemon -L ./ -lprodlib

甚至更简单:

$g++ -c newproduct.cc -o newproduct.o
$g++ main.cc -o daemon newproduct.o