How to specify RPATH in a makefile?

user837208 picture user837208 · Jul 10, 2011 · Viewed 32.5k times · Source

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

Answer

user539810 picture user539810 · Jul 10, 2011

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.