Last updated on October 28, 2019
tl;dr: Save the following file as Makefile and change the source files to the ones that you intend.
# Makefile template for a shared library in C
# https://www.topbug.net/blog/2019/10/28/makefile-template-for-a-shared-library-in-c-with-explanations/
CC = gcc # C compiler
CFLAGS = -fPIC -Wall -Wextra -O2 -g # C flags
LDFLAGS = -shared # linking flags
RM = rm -f # rm command
TARGET_LIB = libtarget.so # target lib
SRCS = main.c src1.c src2.c # source files
OBJS = $(SRCS:.c=.o)
.PHONY: all
all: ${TARGET_LIB}
$(TARGET_LIB): $(OBJS)
$(CC) ${LDFLAGS} -o $@ $^
$(SRCS:.c=.d):%.d:%.c
$(CC) $(CFLAGS) -MM $< >$@
include $(SRCS:.c=.d)
.PHONY: clean
clean:
-${RM} ${TARGET_LIB} ${OBJS} $(SRCS:.c=.d)
The above code snippet is also available on GitHub gist.
Explanation
Basic process: For every C source file (example.c), the C compiler, with the -MM switch, creates a rule file (example.d). The rule file describes the dependencies (e.g., header files) of the object file (example.o) corresponding the C source file. The C compiler then compiles each C source file to an object file. The linker links all object files into the shared library.
- Lines 4–8: The compiler command, compiler flags, linker flags, deletion command, and name of the target library, respectively.
- Line 10: The list of source files.
- Line 11: Object files, inferred from the list of source files by replacing the
.csuffix with.o. - Lines 13–14: The
alltarget depends on the target library target. In other words, building thealltarget, which is the default when runningmake, will have the target library built. - Line 16: The target library depends on the presence of all object files.
- Line 17: Build the target library (
$@) by applying the specified compiler command ($(CC)) with the specified linker flags ($(LDFLAGS)) to all object files ($^). - Line 19: There is a rule file (
*.d) for every C source file. Its file name is determined by replacing the.csuffix with.d. - Line 20: Create each rule file (
$@) by applying to its corresponding C source file ($<) the specified compiler command ($(CC)) with the specified compiler flags ($(CFLAGS)) and the-MMflag. - Line 22: Include the rule files as part of the Makefile.
- Lines 24–26: The
cleantarget, which deletes all generated files (${TARGET_LIB},${OBJS},$(SRCS:.c=.d)) using the deletion command (${RM}). This can be invoked bymake clean.
The post Makefile Template for a Shared Library in C (with Explanations) appeared first on Top Bug Net.


This Post Has 0 Comments