i write simple testing program in c++, tell hello, alex
, exit. here it's code: 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
but when build code make, have such error:
/usr/bin/ld: dll.o: relocation r_x86_64_32 against `.rodata' can not used when making shared object; recompile -fpic
dll.o: error adding symbols: bad value
collect2: error: ld returned 1 exit status
makefile:8: recipe target 'dll.so' failed
make: *** [dll.so] error 1
what did make not correct?
p.s. use gnu make 3.81
on ubuntu server 14.04.3
gnu gcc 4.8.4
update
if link dll.so
file -fpic param, have same error
firstly, bit off topic, in makefile, better specify build_all phony target
.phony: build_all
next, compiling dll.cpp
without relocatable code. need add -fpic
or -fpic
(see here explanation of difference).
$(cxx) -c dll.cpp -fpic
lastly, unix doesn't automatically add file suffixes, here need specify .so
:
$(cxx) -shared -o dll.so dll.o
Comments
Post a Comment