【发布时间】:2017-04-05 19:57:08
【问题描述】:
我用 C++ 编写了一个简单的测试程序,它会告诉Hello, Alex 并退出。
这是代码:
main.cpp:
#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
但是当我用 make 构建我的代码时,我有这样的错误:
/usr/bin/ld: dll.o: relocation R_X86_64_32 against `.rodata' 制作共享对象时不能使用;使用 -fPIC 重新编译
dll.o:添加符号时出错:值错误
collect2:错误:ld 返回 1 个退出状态
makefile:8: 目标“dll.so”的配方失败
make: *** [dll.so] 错误 1
我做错了什么?
附言我在Ubuntu Server 14.04.3 上使用GNU Make 3.81 和GNU GCC 4.8.4
更新
如果我将 dll.so 文件与 -fPIC 参数链接,我会遇到同样的错误
【问题讨论】:
-
您必须使用
-fPIC编译。 链接与-fPIC是没有意义的。
标签: c++ linux makefile shared-libraries gnu-make