gpt4 book ai didi

c++ - linux C++。链接共享对象和主对象

转载 作者:太空宇宙 更新时间:2023-11-04 04:44:50 24 4
gpt4 key购买 nike

我用 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' 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

我做错了什么?
附:我在 Ubuntu Server 14.04.3 上使用 GNU Make 3.81GNU GCC 4.8.4

更新
如果我使用 -fPIC 参数链接 dll.so 文件,则会出现相同的错误

最佳答案

首先,有点偏离主题,但是在 makefile 中,最好将 build_all 指定为虚假目标

.PHONY: build_all

接下来,您将编译没有可重定位代码的dll.cpp。您需要添加 -fpic-fPIC(有关差异的说明,请参阅 here)。

$(CXX) -c dll.cpp -fpic

最后,unix不会自动添加文件后缀,所以这里需要指定.so:

$(CXX) -shared -o dll.so dll.o

关于c++ - linux C++。链接共享对象和主对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43240505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com