Skip to content

Instantly share code, notes, and snippets.

@hallojs
Last active January 4, 2022 18:29
Show Gist options
  • Save hallojs/6e979341be48848bcc038acbaf1dcf78 to your computer and use it in GitHub Desktop.
Save hallojs/6e979341be48848bcc038acbaf1dcf78 to your computer and use it in GitHub Desktop.
Create Static vs. Shared/Dynamic Libraries in C

Static

  • *.A, *.LIB(Windows)
  • Designed to be compiled/linked into the Application
  • Larger codesize, faster

Shared/Dynamic

  • *.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

Example

Structure

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

Makefile

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

MISC

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment