Daniel Ortega
Daniel Ortega

Reputation: 435

Shared library and rpath

I cannot make rpath work properly and make my binary to search for the library in the specified folder:

I have 3 very simple files:

main.c

#include <stdio.h>
#include <func.h>
int main() {
    testing();
return 1;
}

func.h

void testing();

func.c

#include "func.h"
void testing(){

    printf(testing\n");
}

Then I proceed to create a shared library as it follows:

gcc -c -fpic func.c -o ../release/func.o
gcc -shared -o ../release/lib/lib_func.so ../release/func.o

And then compile the program:

gcc main.c ../release/lib/lib_time_mgmt.so -Wl,-rpath=/home/root/ -o ../release/main

I receive the next warning:

main.c:7:2: warning: implicit declaration of function ‘testing’ [-Wimplicit-function-declaration]
testing();

But besides it, the program works fine.

However, my problem is that if now I want to move the library to /home/root (as specified in rpath) it does not work and the library is still searched only in the path specified when I compiled the main.c file which is ../release/lib/lib_time_mgmt.so

What am I doing wrong?


EDIT: After accepting the answer, I leave here the exact line as I used it and made it work for whoever might find it useful:

gcc main.c -L/home/root -Wl,-rpath,'/home/root/' -l:libtime_mgmt -o ${OUT_FILE}

Note: the rpath was used with the path betwen simple '. Not sure if that was the reason why it was not working before, but it worked this way now.

Upvotes: 0

Views: 846

Answers (1)

Attie
Attie

Reputation: 6979

rpath is not used at compile time, but rather at link/runtime... thus you probably need to use both of these:

  • -L /home/root - to link correctly at build time
  • -Wl,-rpath=/home/root - to link correctly at run-time

You should use the -l ${lib} flag to link with libraries, don't specify their path as an input.

In addition to this, convention states that the libraries are named libNAME.so - e.g:

  • -l func will try to link with libfunc.so
  • -l time_mgmt will try to link with libtime_mgmt.so

Once you've addressed the above points, try the following:

gcc main.c -L/home/root -Wl,-rpath=/home/root -lfunc -ltime_mgmt -o ${OUT_FILE}

As a final point, I'd advise that you try not to use rpath, and instead focus on installing libraries in the correct places.


Unrelated to your question, but worth noting. Your use of #include <...> vs #include "..." is questionable. See: What is the difference between #include <filename> and #include "filename"?

Upvotes: 2

Related Questions