2016-09-15 82 views
-3

我已通過多個堆棧溢出職位消失,試圖執行下面的例子與C++對象類 我具有以下的代碼使用的dlopen類對象。未定義參考誤差時用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; 
} 

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