2016-09-15 9 views
-3

Я прошел несколько сообщений о переполнении стека и попытался реализовать следующий пример, который использует dlopen с объектами C++. Класс У меня есть следующий код.Неопределенная ошибка ссылки при использовании объектов класса с C++

1) hello.cc Файл

#include <stdio.h> 
#include "hello.h" 
A::A() { 
    init1(); 
} 
void A::init1() { 
    printf("\n init "); 
} 

2) Файл hello.h

#include <iostream> 
class A { 
    public: 
     A(); 
     void init1(); 
     inline void fun() { cout << "\n Inside fun"; } 
}; 


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

}

3) Файл main.cpp

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

Я используя следующие шаги для создания общей библиотеки

1) g++ -g -fPIC -c hello.cc 
2) g++ -g -shared -o libhello.so hello.o 
3) g++ -g -o myprog main.cpp - 

main.cpp:(.text+0x18): undefined reference to `A::A()' . The function createA in hello.h is declared so the same can be used to dlsym 
  1. Я не могу использовать createA в dlsym
  2. Я получаю неопределенную ссылку на `A :: A(), даже если я не использую dlsym
  3. Мой запрос является то, что правильно было использовать ++ объекты класса C в dlsym
  4. от человека dlopen я не могу сделать вывод, что значение RTLD_LAZY RTLD_GLOBAL RTLD_NOW флагов
+0

C не может обрабатывать классы. –

+0

Это код C++ – TechEnthusiast

+0

'extern 'C" A * createA() 'явно говорит, что это не так. –

ответ

0

Просто поместите в командной строке:

g++ -g -o myprog main.cpp -l hello -l dl -L ./ 

и, конечно, - если вы хотите, чтобы запустить его локально, необходимо скомпилировать с -rpath

.. -Wl,-rpath ./ 
0

скорректированным hello.h:

/* hello.h */ 

#include <cstdio> 

class A { 
    public: 
     A(); 
     void init1(); 
     inline void fun() { printf ("A::fun (this=%p)\n", this); } 
}; 

extern "C" A* createA(); 

hello.cc:

/* hello.cc */ 

#include <cstdio> 

#include "hello.h" 

A::A() { 
    init1(); 
} 

void A::init1() { 
    printf("A::init1 this=%p\n", this); 
} 

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

основная.cc:

/* main.cc */ 

#include <cstdio> 
#include <iostream> 
#include <dlfcn.h> 
#include "hello.h" 

using namespace std; 

typedef A *fun_createA(); 

int main() { 
    void *handle; 
    fun_createA *ptr_createA; 
    A *myA; 

    handle = dlopen("./libhello.so", RTLD_LAZY | RTLD_GLOBAL); 
    if (!handle) { 
     cout << "The error is " << dlerror(); 
    } 
    ptr_createA = (fun_createA *)dlsym (handle, "createA"); 
    printf ("ptr_createA is %p\n", ptr_createA); 

    myA = ptr_createA(); 
    printf ("ptr_createA gave me %p\n", myA); 

    myA->fun(); 

    return 0; 
}