Skip to content

Instantly share code, notes, and snippets.

@mrprajesh
Last active December 29, 2022 00:24
Show Gist options
  • Save mrprajesh/4229185c0047d5d165480d82866c6037 to your computer and use it in GitHub Desktop.
Save mrprajesh/4229185c0047d5d165480d82866c6037 to your computer and use it in GitHub Desktop.
Understanding `gcc` compile options
gcc -c -Wall main.c
gcc -c -Wall -fPIC foo.c bar.c

gcc -shared foo.o -o libfoo.so 
gcc -shared bar.o -o libbar.so 

gcc -c -Wall -fPIC foobar.c  //can be add to 2.

gcc -shared foobar.o -o libfoobar.so -L. -lfoo -lbar                 //ORIGINAL: note the lib is omitted
gcc -shared foobar.o -o libfoobar.so -L. -lfoo -lbar -Wl,-rpath,.    //EDITED 
// whenever creating the .so use  -Wl,-rpath,. lib in that dir 

gcc -o prog main.o -L. -lfoobar -Wl,-rpath-link=$(pwd) // let's not use this.
gcc -o prog main.o -L. -lfoobar -Wl,-rpath=$(pwd)  // try this
gcc -o prog main.o -L. -lfoobar -Wl,-rpath,.      //EDITED: oops = is not very compatible across OS's seems

# would error if we do not include LD PATH
./prog 
./prog: error while loading shared libraries: libfoo.so: cannot open shared object file: No such file or directory

LD_LIBRARY_PATH=. ./prog
foo
bar

#EDITED. Should find the ld path at run time. 
./prog
foo
bar

Reference

https://stackoverflow.com/a/49181161/2712045

Discussion for another day.

What is -Wl?

ld aaa bbb ccc ===> gcc -Wl,aaa -Wl,bbb -Wl,ccc =>gcc -Wl,aaa,bbb,ccc

Wl,-rpath,dir1,-rpath,dir2 ~= -Wl,-rpath=dir1,-rpath=dir2

-Wl,-rpath,. means -Wl,-rpath -Wl,.

Source: https://stackoverflow.com/a/6562437/2712045

what is -fPIC?

PIC: This would work whether the code was at address 100 or 1000
100: COMPARE REG1, REG2
101: JUMP_IF_EQUAL CURRENT+10
...
111: NOP


Non-PIC: This will only work if the code is at address 100
100: COMPARE REG1, REG2
101: JUMP_IF_EQUAL 111
...
111: NOP
EDIT: In response to comment.

If your code is compiled with -fPIC, it's suitable for inclusion in a library - the library must be able to be relocated from its preferred location in memory to another address, there could be another already loaded library at the address your library prefers.

Source: https://stackoverflow.com/a/5311538/2712045

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment