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 libname.so 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 LD_LIBRARY_PATH=. export LD_LIBRARY_PATH
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: libname.so: 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.
LD_LIBRARY_PATH=. 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
If you compile your program using
gccdirectly (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
gccmanually or by running
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_PATHbut also from the
DT_RUNPATHinformation in the executable.
LD_LIBRARY_PATHvariable which is set on one console (or terminal) only, the
DT_RUNPATHinformation is stored directly in the executable file.
As described in another question on this site, you can set the
DT_RUNPATHinformation using the
gcc -L. main1.c -lname -o out -Wl,-rpath=.
If you do this, the dynamic linker will search your library (
libname.so, 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
./somedirand you type
somedir/out, the file
./libname.sois searched, not the file
This is both the case for the
-Wl,-rpath=method and for the