*.A
, *.LIB
(Windows)
- Designed to be compiled/linked into the Application
- Larger codesize, faster
*.SO
(Linux), .DYLIB
(MacOS), *.DLL
(Windows)
- Designed to be loaded at runtime
- Smaller codesize, slower
- Run with
LD_LIBRARY_PATH="PATH-TO-YOUR-LIBRARY"./EXECUTABLE
mylib_c/
|-- include
| `-- mylib.h
|-- lib
| |-- libmylib.so
| `-- libmystaticlib.a
`-- src
|-- Makefile
|-- mylib.c
|-- obj
| |-- mylib.o
| `-- test.o
|-- test.c
|-- test.out
|-- test_shared.out
`-- test_static.out
IDIR = ../include
CC = gcc
CFLAGS = -I$(IDIR)
ODIR = obj
LDIR = ../lib
_DEPS = mylib.h
DEPS = $(patsubst %,$(IDIR)/%,$(_DEPS))
_OBJ = mylib.o test.o
OBJ = $(patsubst %,$(ODIR)/%,$(_OBJ))
all: test.out test_shared.out test_static.out
$(ODIR)/%.o: %.c $(DEPS)
$(CC) -c -o $@ $< $(CFLAGS)
# Create a dynamic library
# - fPIC: Compiler generates position-independent code. This code runs
# independent from the memory position it was loaded into.
# - shared: Compiler outputs shared myliblibrary.
# - IMPORTANT: The file has to start with the prefix lib
$(LDIR)/libmylib.so: mylib.c
$(CC) -fPIC -shared -o $@ $^ $(CFLAGS) -lc
# Create a static library
$(LDIR)/libmystaticlib.a: obj/mylib.o
ar rcs $@ $<
# Use object file of mylib to generate app
test.out: $(OBJ)
$(CC) -o $@ $^ $(CFLAGS)
# Use shared library to generate app
test_shared.out: test.c $(LDIR)/libmylib.so
$(CC) -o $@ $< $(CFLAGS) -L$(LDIR) -lmylib
# Use static library to generate app
test_static.out: test.c $(LDIR)/libmystaticlib.a
$(CC) -o $@ $< $(CFLAGS) -L$(LDIR) -lmystaticlib
.PHONY: clean
clean:
rm -f $(ODIR)/*.o $(LDIR)/*.so *.out