Вопрос

I'm trying to create a library with a source file and then use this library in my program. But linker throws error regarding vtable:

Following is the code:

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;
}

I'm trying to run the following steps:

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

But this gives me error:

/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

Can you please suggest what is going wrong above??

Thanks

Это было полезно?

Решение

To make a shared .so file, you could do like this:

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

Or even simpler:

$g++ -c newproduct.cc -o newproduct.o
$g++ main.cc -o daemon newproduct.o
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top