如何为C创建和运行make文件?
我有3个文件如何为C创建和运行make文件?,c,makefile,C,Makefile,我有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
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 $<
结果:hellomain.o hellofunc.o
gcc$^-o结果
hellomain.o:hellomain.c helloheader.h
gcc-c$<
hellofunc.o:hellofunc.c helloheader.h
gcc-c$<
确保在makefile中使用制表符进行缩进。makefiles有数千个示例和教程。从复制一个简单的开始,然后从那里开始工作。另外,您不应该真正构建头文件。我尝试了下面的示例:但无法使其工作。虽然您所遵循的示例得到了很好的评论,但它并不是很简单(IMO)。我会写一个非常简单的makefile。等等。如果你只需要缩短你的命令,只需要做一个或一个。或者,如果您使用的是Windows,则为。只有当您希望尽可能缩短编译时间时,您才需要一个makefile,如果您只有两个源文件,任何此类优化都不会有意义。因此,请将您发布的最基本版本粘贴到makefile中,以将其测试到一个没有任何扩展名的makefile中。但当我键入make并按enter键时,我发现***缺少分隔符。停止。@DanielD命令前的空格必须是制表符。不可能是四个空格。你必须编辑文件以确保它们是选项卡。啊,对了,忘了,记得也读过了!谢谢你,现在我可以在此基础上构建:)删除第二行可以进一步简化“最简单的Makefile”。内置规则会处理好的。