我有3个文件
hellomain.c
hellofunc.c
helloheader.h
我正在通过 GCC 编译器运行。通常我会输入:
gcc helloheader.h hellomain.c hellofunc.c -o results
一切都会运行。
如何将其转换为 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
它可以更简单,但是有了这个你就有了一些灵活性。
为了完整起见,这可能是最简单的 makefile:
results: hellomain.c hellofunc.c helloheader.h
$(CC) hellomain.c hellofunc.c -o results
这基本上就是您已经在命令行上执行的操作。它不是很灵活,如果任何文件发生变化,它会重建所有内容。
这是带有硬编码文件名的
makefile
。它很容易理解,但当您添加/删除源文件和头文件时,更新可能会很乏味。
results: hellomain.o hellofunc.o
gcc $^ -o results
hellomain.o: hellomain.c helloheader.h
gcc -c $<
hellofunc.o: hellofunc.c helloheader.h
gcc -c $<
确保在 makefile 中使用制表符进行缩进。
SRC:https://makefiletutorial.com/
blah: blah.o
cc blah.o -o blah # Runs third
blah.o: blah.c
cc -c blah.c -o blah.o # Runs second
# Typically blah.c would already exist, but I want to limit any additional required files
blah.c:
echo "int main() { return 0; }" > blah.c # Runs first
然后
$ make