我有3个文件
hellomain.c
hellofunc.c
helloheader.h
Run Code Online (Sandbox Code Playgroud)
我正在通过 GCC 编译器运行。通常我会输入:
gcc helloheader.h hellomain.c hellofunc.c -o results
Run Code Online (Sandbox Code Playgroud)
一切都会运行。
如何将其转换为 makefile?我知道我必须给它加上标题makefile。我知道我必须通过make在编译器中输入来调用它。但不确定在 makefile 中实际输入什么。
对于像您这样的项目来说,最简单的 makefile 可能是这样的:
# The name of the source files
SOURCES = hellomain.c hellofunc.c
# The name of the executable
EXE = results
# Flags for compilation (adding warnings are always good)
CFLAGS = -Wall
# Flags for linking (none for the moment)
LDFLAGS =
# Libraries to link with (none for the moment)
LIBS =
# Use the GCC frontend program when linking
LD = gcc
# This creates a list of object files from the source files
OBJECTS = $(SOURCES:%.c=%.o)
# The first target, this will be the default target if none is specified
# This target tells "make" to make the "all" target
default: all
# Having an "all" target is customary, so one could write "make all"
# It depends on the executable program
all: $(EXE)
# This will link the executable from the object files
$(EXE): $(OBJECTS)
$(LD) $(LDFLAGS) $(OBJECTS) -o $(EXE) $(LIBS)
# This is a target that will compiler all needed source files into object files
# We don't need to specify a command or any rules, "make" will handle it automatically
%.o: %.c
# Target to clean up after us
clean:
-rm -f $(EXE) # Remove the executable file
-rm -f $(OBJECTS) # Remove the object files
# Finally we need to tell "make" what source and header file each object file depends on
hellomain.o: hellomain.c helloheader.h
hellofunc.o: hellofunc.c helloheader.h
Run Code Online (Sandbox Code Playgroud)
它甚至可以更简单,但这样你就有了一定的灵活性。
为了完整起见,这可能是最简单的 makefile:
results: hellomain.c hellofunc.c helloheader.h
$(CC) hellomain.c hellofunc.c -o results
Run Code Online (Sandbox Code Playgroud)
这基本上就是在命令行上执行的操作。它不是很灵活,如果任何文件发生更改,它会重建所有内容。