I am getting undefined reference for cusing class objects in shared libraries and dlopen

FILE main.cpp
#include<iostream>
#include<dlfcn.h>
#include "hello.h"
using namespace std;
typedef A* (*creatorFunction)();
int main()
{
void *handle;
handle = dlopen("./libhello.so", RTLD_LAZY | RTLD_GLOBAL);
if (!handle)
{
cout << "The error is " << dlerror();
}

A* a = new A;


return 0 ;
}


/*hello.c*/
#include <stdio.h>
#include "hello.h"
A::A() {

init1();
}

void A::init1() {

printf("\n init ");
}

/*hello.c*/
#include <stdio.h>

class A {
public:
A();
void init1();
void fun () { printf("\n Inside fun"); }
};

extern "C" A* createA() {
return new A;

}


g++ -g -fPIC -c hello.cc
g++ -g -shared -o libhello.so hello.o
g++ -g -o myprog main.cpp -

main.cpp:(.text+0x18): undefined reference to `A::A()'


how to solve this
1) Please use code tags when posting code, to make it readable:

http://www.cplusplus.com/articles/z13hAqkS/

2) This is a linker error. I suspect this is something to do with not correctly linking dynamically with the shared library, but I don't know much about how this works on Linux, so I'll leave that to others to answer.
Last edited on
You cannot create an object of the type A with new since the constructor is not defined within your program.

Therefore you have defined the creatorFunction. You need to search in the loaded library for the function createA. Then use that function pointer (if found) to create an object of the type A.

It looks like that's the whole point of that exercise.

Take a look at the example:

http://linux.die.net/man/3/dlopen
Topic archived. No new replies allowed.