【问题标题】:How to create a makefile in gcc如何在 gcc 中创建 makefile
【发布时间】:2025-12-04 15:45:01
【问题描述】:

我正在尝试创建一个 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?

【问题讨论】:

  • 你为什么使用DOS?这是一个过时的操作系统!你不能在你的笔记本电脑上安装Debian 吗?您可以使用GNU emacs 创建您的Makefile(对于GNU make...)。使用GCC,请使用gcc -Wall -Wextra -g 进行编译,然后使用GDB 了解可执行文件的行为
  • 另见 thisthat 答案。
  • 你真的在使用 DOS 吗?
  • 非常感谢您的重播,请清除我,我们无法在 windows 7 中创建 makefile?我们只需要使用 debin 或 linux 吗?
  • 两个文件是否在同一个文件夹中? makefile 是否在您正在使用的工具的正确文件夹中?

标签: c windows makefile


【解决方案1】:

在我看来你没有掌握make(1)的精髓:

  • 在 makefiles 中存储您构建目录中的一组依赖关系规则(文件之间的依赖关系),以便构建您的项目。
  • 有依赖行和构建行,依赖从行的第 0 列开始,而构建行以制表符开头。
  • 规则行有两部分,要构建的文件、冒号 (:) 和它所依赖的文件列表(这样如果其中一个或多个文件被修改,规则被应用)
  • 如果必须应用规则,则执行规则下方的一组构建行(直到找到下一条规则或变量定义规则)以构建文件。

示例

你的文件hello.c会被编译成hello.s来创建一个汇编文件,然后汇编代码生成一个目标代码hello.o。最后,链接此文件以生成文件hello(或hello.exe,如果您在Windows 中)。

您安排您的 makefile 以生成所有文件,如果您修改例如汇编程序文件hello.s,只有汇编程序通道和链接器通道已完成,但没有在汇编之前应该覆盖汇编程序文件的编译阶段。这可以通过这个 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 的完整文档)

【讨论】: