20

I'm trying to specify rpath in my binary. My makefile looks like this-

CC=gcc 
CFLAGS=-Wall
LDFLAGS= -rpath='../libs/'
main: main.c  
    gcc -o main main.c

clean:
    rm -f main main.o 

But when I query rpath using command readelf -a ./main | grep rpath I get nothing I've tried specifying rpath as LDFLAGS= "-rpath=../libs/" but even that doesn't seem to work.

Can someone please post an example on how should I specify rpath in a makefile?

GCC and ld versions are-

gcc (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2
GNU ld (GNU Binutils for Ubuntu) 2.21.0.20110327
jww
  • 97,681
  • 90
  • 411
  • 885
user837208
  • 2,487
  • 7
  • 37
  • 54

1 Answers1

48

If you set the variables, you should probably use them. It's silly not to, especially when make won't magically set those variables for you! :)

main: main.c
    $(CC) $(CFLAGS) $(LDFLAGS) -o main main.c

Another problem is LDFLAGS, it should be

LDFLAGS="-Wl,-rpath,../libs/"

The usual gcc switch for passing options to linker is -Wl,, and it is needed because gcc itself may not understand the bare -rpath linker option. While some builds of various versions of gcc accept -rpath, I have never seen it documented in gcc man pages or info pages. For better portability, -Wl,-rpath should be preferred.

  • 1
    After updating makefile, I get below error- gcc: unrecognized option '-rpath=../libs/' – user837208 Jul 10 '11 at 01:22
  • 4
    It's a tiny point but, in case anyone was wondering, just to add that complete paths are also valid in the rpaths like `LDFLAGS="-Wl,-rpath,/mnt/us/extensions/thing/usr/lib/"` – twobob Oct 05 '13 at 22:01
  • 1
    @twobob Do you know that the value of rpath can be symlink ? – szydan Apr 10 '15 at 01:00
  • @szydan that was on a FAT drive, sadly would be detected as a cross link and nerfed I think. I tend to use http://gcc.gnu.org/ml/gcc/1999-04n/msg01105.html these days after the fact. – twobob Apr 10 '15 at 15:41
  • How about generating the rdpath from `realpath`? That seems to be the only way I can make a dynamically linked program work from several directories (as in `bin/prog` vs. `prog` from `bin/` and libraries in a separate directory like `lib`.) That's also the way I associate resources like shaders. – John P Oct 07 '17 at 19:07
  • Thank you! exactly what the problem was on my system! – Sujay Phadke Dec 11 '17 at 11:41