我用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:在创建共享对象时,不能使用针对`.rodata'的重定位R_X86_64_32;用-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
Update
如果我用-fPIC param链接 dll.so
文件,我有同样的错误
1 回答
首先,有点偏离主题,但在你的makefile中,最好将build_all指定为虚假目标
接下来,您正在编译
dll.cpp
而没有可重定位代码 . 您需要添加-fpic
或-fPIC
(有关区别的说明,请参阅here) .最后,unix不会自动添加文件后缀,所以在这里你需要指定
.so
: