22 Ekim 2013 Salı

Simple Makefile Including Compilation of Shared Object Library

This post covers two main concepts: a simple Makefile generation and compiling a shared object library within this Makefile.
Directory structure is designed as this:

  • ../MakeFileProj (MakeFile)
  • ../MakeFileProj/inc (Headers: test1.h, test2.h)
  • ../MakeFileProj/src (Source Files: main.c test1.c test2.c)
  • ../MakeFileProj/obj (Object Files: main.o test1.o test2.o)
  • ../MakeFileProj/lib (Library Files: libtest2.so -> test2.c is compiled as shared object library)

The source and header files are given below:

Makefile is as shown below:
As source, test1.c and main.c are compiled and object files are created under /obj directory. However test2.c is compiled as a shared object library and the .so file created under /lib. Finally, the object files and the .so library are linked to create "test" executable.

After compilation succesfully one can try the executable file in console as:
$ ./test
$ ./test: error while loading shared libraries: libtest2.so: cannot open shared object file: No such file or directory
At run-time the executable file cannot find shared object library, so we should add it to LD_LIBRARY_PATH.
$ export LD_LIBRARY_PATH=/home/sezerb/Desktop/MakeFileProj/lib:$LD_LIBRARY_PATH
Do not forget to use your own path, where libtest2.so is located. Then try ./test again:
$ ./test
$ sZr Welcome to MakeFileProject...
$ sZr test1Message: This is not a shared library
$ sZr test2Message: This is a SHARED LIBRARY

This Makefile should be a reference one for our projects...
Take care yourselves!..