2017-04-05 57 views
-1

我用C++編寫簡單的測試程序,它會告訴Hello, Alex並退出。 這是代碼: main.cpplinux C++。鏈接共享對象和主文件

#include <iostream> 
#include <dlfcn.h> 


int main() 
{ 
    void* descriptor = dlopen("dll.so", RTLD_LAZY); 
    std::string (*fun)(const std::string name) = (std::string (*)(const std::string)) dlsym(descriptor, "sayHello"); 

    std::cout << fun("Alex") << std::endl; 

    dlclose(descriptor); 
    return 0; 
} 

dll.h

#ifndef UNTITLED_DLL_H 
#define UNTITLED_DLL_H 

#include <string>  
std::string sayHello(const std::string name); 
#endif 

dll.cpp

#include "dll.h" 

std::string sayHello(const std::string name) 
{ 
    return ("Hello, " + name); 
} 

makefile

build_all : main dll.so 

main : main.cpp 
    $(CXX) -c main.cpp 
    $(CXX) -o main main.o -ldl 

dll.so : dll.h dll.cpp 
    $(CXX) -c dll.cpp 
    $(CXX) -shared -o dll dll.o 

但是當我建立我的化妝代碼,我有這樣的錯誤:

/usr/bin/ld: dll.o: relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
dll.o: error adding symbols: Bad value
collect2: error: ld returned 1 exit status
makefile:8: recipe for target 'dll.so' failed
make: *** [dll.so] Error 1

什麼我都做不正確?
P.S.我對Ubuntu Server 14.04.3使用GNU Make 3.81與​​

更新
如果我鏈接dll.so文件,-fPIC PARAM,我也有同樣的錯誤

+0

您必須*編譯*用'-fPIC'。 *用'-fPIC'連接*沒有意義。 – Beta

回答

2

首先一點題外話,但在你的makefile,這將是更好的爲假目標

.PHONY: build_all 

下一頁註明build_all,你是不重定位代碼編譯dll.cpp。您需要添加-fpic-fPIC(有關差異的解釋,請參閱here)。

$(CXX) -c dll.cpp -fpic 

最後,UNIX不會自動添加文件後綴,所以在這裏你需要指定.so

$(CXX) -shared -o dll.so dll.o