我用C++編寫簡單的測試程序,它會告訴Hello, Alex
並退出。 這是代碼: main.cpp
:linux 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,我也有同樣的錯誤
您必須*編譯*用'-fPIC'。 *用'-fPIC'連接*沒有意義。 – Beta