- Lab 1: Libraries and Makefile
Tasks for today:
- Building a static library and a dynamic library
- Create a Makefile to build an executable along with your library
- Write a C program to print Hello!
- where is printf defined?
- what is libary?
- Create our own library
- Create a function: calc.c
- static vs. dynamic
- Create a static library:
- $ gcc -c -o calc.o calc.c
- $ ar rs libcalc.a calc.o
- Create a dynamic library:
- $ gcc -c -fPIC -o calc.o calc.c
- $ gcc -shared -o libcalc.so calc.o
- -fPIC: position-independent code. Necessary for shared library
- -shared: Necessary when producing shared library
- Create a header file, calc.h.
- To organize the code, put calc.h to include directory, libcalc.a and libcalc.so to lib
- Write a program to use our library
- To use the library: $ gcc -I./include -L./lib -o test test.c -lcalc
- -I to specify the path of our header file
- -L to specify the path of our library
- -o to specify the output file
- why we don't use -I and -L when calling printf()?
- Before you run test, export LD_LIBRARY_PATH=/path/to/our/library:$LD_LIBRARY_PATH
- What if we want to change the implementation of mean()? Twice? 15 times?
- Use Makefile
- Why do we need a Makefile
- No need to type the compiling command everytime
- No need to recompile everything everytime
- Basic Syntax
- Now modify mean() function again and compile.
Author: Zhuoqun (Tom) Cheng.