[英]How to create a makefile in gcc
我正在尝试创建 makefile 但面临一些问题。 我在 Windows 7 中安装了 gcc 编译器,然后创建了一个简单的 helloworld 示例。 之后使用以下命令编译该 C 文件:
gcc filename.c
在此之后,我得到一个 exe 文件。 我在一些工具中调用这个项目,工具需要makefie。
据我了解 makefile 是一个文本文件,它告诉或包含一些命令如何构建、运行和清理项目。
所以据此我正在写一个makefile:
CC=gcc
SRCS=src/hello.c
.PHONY: all
all: clean build
@echo ========== Complete ==========
.PHONY: build
build:
@echo ========== Build ==========
$(CC) hello.c
.PHONY: run
run:
@echo ========== Run ==========
make
.PHONY: clean
clean:
@echo ========== Clean ==========
rm hello.exe
./obj:
mkdir ./obj
在工具中调用这个简单的项目时,出现错误“没有规则使目标干净”
请告诉我我遵循的哪些步骤对于创建 makefile 是否正确,我在做什么错误? 如何创建 makefile?
在我看来,您还没有掌握 make(1) 的精髓:
:
和它所依赖的文件列表(因此,如果修改了这些文件中的一个或多个,则应用规则)你的文件hello.c
将被编译成hello.s
来创建一个汇编文件,然后汇编代码生成一个 object 代码hello.o
。 最后,链接该文件以生成文件hello
(或hello.exe
,如果您在 Windows 中)。
你安排你的 makefile 生成所有文件,如果你修改例如汇编文件hello.s
,只有汇编程序通过,并且 linker 通过完成,但不是应该在汇编之前覆盖汇编文件的编译阶段. 这可以通过这个 Makefile 来完成:
# this is the linking phase. The first rule in the file is the
# default target rule, so by default, executing make will try this
# rule (but only if hello.exe was modified before hello.o)
hello.exe: hello.o
gcc -o hello.exe hello.o
# Now, the assembling phase. The hello.o file depends on the
# hello.s assembly code, so to assemble it we call the assembler
hello.o: hello.s
as -o hello.o hello.s
# now, we specify the dependency from the hello.s assembler file
# from the hello.c source code file.
hello.s: hello.c
gcc -c -S -o hello.s hello.c
现在,如果这是您第一次执行 make 并且您只有文件hello.c
(当然还有Makefile
),那么 make 程序将生成以下命令序列:
$ make
gcc -c -S -o hello.s hello.c
as -o hello.o hello.s
gcc -o hello.exe hello.o
$ _
但是如果您稍后修改文件hello.s
(我将touch(1)
它,以更改其修改日期:
$ touch hello.s
$ make
as -o hello.o hello.s
gcc -o hello.exe hello.o
$ _
但是如果你触摸hello.c
,一切都会再次发生:
$ touch hello.c
$ make
gcc -c -S -o hello.s hello.c
as -o hello.o hello.s
gcc -o hello.exe hello.o
$ _
Make 构建一个依赖图并遵循它以构建您在命令行中指定的目标,因此如果您将 make 与目标一起使用,它将在构建目标后立即停止:
$ make hello.o
gcc -c -S -o hello.s hello.c
as -o hello.o hello.s
$ _
我建议你读一本关于制作的书。 一个很好的是 GNU Make 文档,它作为信息文件在您的系统上在线:只需执行:
$ info make
(并且info
将打开一个文本屏幕,让您阅读make
的完整文档)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.