2017-04-05 4 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.私は-fPICのparamでdll.soファイルをリンクした場合、私は​​

更新
Ubuntu Server 14.04.3GNU Make 3.81を使用し、私は

+0

あなたは* '-fPIC'で*コンパイルする必要があります。 * '-fPIC'とのリンクは無意味です。 – Beta

答えて

2

まず同じエラー、トピックオフビットを持っていますが、あなたのメイクファイルで、それは次のようになりますより良い偽のターゲット

.PHONY: build_all 

次のようbuild_all指定するには、再配置可能なコードなしでdll.cppをコンパイルしています。 -fpicまたは-fPICを追加する必要があります(違いの説明については、hereを参照してください)。

最後に、UNIXは自動的にあなたが .soを指定する必要がありますので、ここで、ファイルの拡張子を追加しません
$(CXX) -c dll.cpp -fpic 

$(CXX) -shared -o dll.so dll.o 
関連する問題