Search code examples
linkerg++linker-flags

I want to know what happened when I use the command "g++ -o main main.o -L<directory> -l<lib_name>"


Supposing I have main.c main.o libheymath.so in current directory. I want to link them together to generate an executable file. I use command "g++ -o main main.o -L./ -lheymath" to realize that. But I don't know why I should indicate the library directory and name. As far as I know, when I run "./main" the system will load the shared library into memory in specific directories such as /lib and /use/lib and directories specified in LD_LIBRARY_PATH etc. but not what I have indicated. So what's the purpose of "-L./ -lheymath"?

working directory files:

main.c, main.o, libheymath.so

command:

g++ -o main main.o -L./ -lheymath

./main


Solution

  • -L allows to indicates a path where to look to find lib(s) at link time (it is not 'saved' in the produced executable to be reused when you will launch the executable)

    -l indicates a lib you want to link with, this allows to check if some symbols are missing or not and to know the list of libs to load when you will launch the executable.

    When you link the path of these libs is not saved into the executable because both executable and libs can be moved after the link (and may be installed on an other host)

    Note LD_LIBRARY_PATH is used when you start an executable to find the dynamic libs, it is not used when you link objects/libs to make an executable