簡體   English   中英

如何在 gcc 中創建 makefile

[英]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) 的精髓:

  • 在 makefiles 中存儲您的構建目錄中的一組依賴關系規則(文件之間的依賴關系),以便構建您的項目。
  • 有依賴行和構建行,依賴從行的第 0 列開始,而構建行以制表符開頭。
  • 規則行有兩部分,要構建的文件、冒號 ( :和它所依賴的文件列表(因此,如果修改了這些文件中的一個或多個,則應用規則)
  • 如果必須應用規則,則執行規則下方的一組構建行(直到找到下一個規則或變量定義規則)以構建文件。

例子

你的文件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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM