Linux C++.链接共享对象和主对象
linux C++. Link shared objects and main
我用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 个退出状态
生成文件:8:目标"dll.so"配方失败
生成:*** [dll.so] 错误 1
我做了什么不对?
附言我在Ubuntu Server 14.04.3
上使用GNU Make 3.81
GNU GCC 4.8.4
更新
如果我使用 -fPIC 参数链接dll.so
文件,我会遇到同样的错误
首先,有点跑题了,但是在您的makefile中,最好将build_all指定为虚假目标
.PHONY: build_all
接下来,您将编译dll.cpp
而不使用可重定位的代码。您需要添加-fpic
或-fPIC
(有关差异的说明,请参阅此处(。
$(CXX) -c dll.cpp -fpic
最后,unix 不会自动添加文件后缀,所以这里你需要指定.so
:
$(CXX) -shared -o dll.so dll.o
相关文章:
- 如何从具有移动语义的类对象中生成共享指针
- 使用共享指针的函数调用,其对象应为 const
- 处理影响跨不同线程共享对象的定时回调的最佳方法是什么?
- 在共享缓冲区内存中创建 ::std::string 对象
- 如何创建一个共享对象与另一个.所以在Cmake
- 内联函数的函数本地静态对象是否在共享对象文件之间共享?
- 有没有办法列出所有共享内存对象的名称?
- 共享的从属对象
- 在 Android Studio 中使用 C++ 共享对象时出现问题
- 共享对象、符号、C/C++ 库链接和加载
- ./main:加载共享库时出错:libopencv_highgui.so.4.0:无法打开共享对象文件:没有这样的文件或
- 在 win32 上生成 R 包:无法加载共享对象 (.dll)
- C++对象共享属性 - 使用指针或引用
- 如何测试共享对象/共享库已正确编译
- 创建对象共享指针以共享指针为参数
- 限制C++中虚拟基类的对象共享
- 在Ada95中跨共享库/对象共享数据
- 这种线程间对象共享策略是否合理
- 如何更改对象共享指针指向,而它被其他线程占用
- 初始化仅由一组对象共享的静态变量