-1

I write simple testing program in C++, which will tell Hello, Alex and 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 I build my code with make, I have such error:

/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

What did I make not correct?
P.S. I use GNU Make 3.81 on Ubuntu Server 14.04.3 with GNU GCC 4.8.4

Update
If I link dll.so file with -fPIC param, I have the same error

AJIOB
  • 329
  • 5
  • 12

1 Answers1

2

Firstly, a bit off topic, but in your makefile, it would be better to specify build_all as a phony target

.PHONY: build_all

Next, you are compiling dll.cpp without relocatable code. You need to add -fpic or -fPIC (see here for an explanation of the difference).

$(CXX) -c dll.cpp -fpic

Lastly, unix doesn't automatically add file suffixes, so here you need to specify .so:

$(CXX) -shared -o dll.so dll.o
Community
  • 1
  • 1
Paul Floyd
  • 5,530
  • 5
  • 29
  • 43