Search code examples
cgccgnulddynamic-library

GNU C : How can I compile a C program with dynamic library option -lmylib but without -L option


I have used several libraries for example pthread as -lpthread and math as -lmath but I need not use the -L option to specify linking path.

But,

  1. I created a library mylib by compiling my program mylib.c as gcc -fPIC mylib.c -o libmylib.so
  2. placed it in /usr/local/lib/libcustom
  3. Added path /usr/local/lib/libcustom into a file /etc/ld.so.conf.d/libcustom.conf
  4. run ldconfig
  5. run export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib/customlib
  6. created a sample.c called the function in mylib

Now when I compile sample.c a gcc -L /usr/local/lib/customlib -o sample.o -lmylib it work fine where as when I try gcc sample.c -o sample.o -lmylib it gives ld error as /usr/bin/ld: cannot find -lmylib

I want to know why is -L flag optional in case of -lpthread and mandatory in case of -lmylib? How can I skip the use of -L in case of -lmylib?

Thanks.


Solution

  • You're looking for LIBRARY_PATH.

    LD_LIBRARY_PATH is for loading dynamic libraries at runtime, not compile time.


    Side note: when adding on to existing environment variables, make sure to use $LD_LIBRARY_PATH instead of just LD_LIBRARY_PATH. Otherwise, you're discarding the original contents and putting in the literal text LD_LIBRARY_PATH.

    So it should change from:

    export LD_LIBRARY_PATH=LD_LIBRARY_PATH:/usr/local/lib/customlib
    

    to:

    export LIBRARY_PATH=$LIBRARY_PATH:/usr/local/lib/customlib