Compiling dynamically linked library in a makefile

I am trying to run my library using a make file. I currently have a dynamic library called which I created by linking the object files of some of my C files. This library works correctly when I run the following lines of code in my linux shell :

   gcc -L. main1.c -lname -o out

But when I copy these exact lines of code in to a make file and name the make file title for this function 'names' and then run 'make names' in linux shell, I get the following error:

./out: error while loading shared libraries: cannot open shared object file: No such file or directory

Then once again when I run the final two lines of code shown at the end of the makefile function again then run the out file, it is fixed and the program works again.

I just need to figure out how to make it work directly from the makefile.

1 answer

  • answered 2022-01-25 07:50 Martin Rosenau

    export LD_LIBRARY_PATH

    These two lines do not influence the creation of the program in any way because you type the lines after creating the program.

    These lines are not used for building your program, but they influence running the program (by typing ./out).

    If you compile your program using gcc directly (not using make) and open a new terminal, you also have to type these two lines (again) before you run the program.

    It does not matter how you build the program (by typing gcc manually or by running make):

    After opening a new terminal, you will need to type these two lines before you run the program.

    However, the dynamic linker does not only use the path information from LD_LIBRARY_PATH but also from the DT_RUNPATH information in the executable.

    Unlike the LD_LIBRARY_PATH variable which is set on one console (or terminal) only, the DT_RUNPATH information is stored directly in the executable file.

    As described in another question on this site, you can set the DT_RUNPATH information using the -Wl,-rpath=<value> switch:

    gcc -L. main1.c -lname -o out -Wl,-rpath=.

    If you do this, the dynamic linker will search your library (, if I understand correctly) in the current directory.


    . really means: In the current directory; it does not mean: In the same directory as the executable file!

    If your program is stored in the directory ./somedir and you type somedir/out, the file ./ is searched, not the file ./somedir/

    This is both the case for the -Wl,-rpath= method and for the LD_LIBRARY_PATH= mehtod.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum