訂閱
糾錯(cuò)
加入自媒體

make 識(shí)別不出 .h 頭文件的修改,怎么回事?

最簡(jiǎn)單、無(wú)腦的方法

既然知道了原因,那就好辦了,我們手動(dòng)把頭文件 hello.h 加到依賴中,不就可以了嗎?!

把 Makefile 中最后面幾句修改成下面這樣:

HEADERS := hello.h
%.o: %.c ${HEADERS}
gcc $< -c -o $@

也就是把 .h 文件,也加入到 .o 文件的依賴中,這樣的話,每次修改 .h 文件后,再執(zhí)行 make 指令時(shí),就可以重新編譯 .o 目標(biāo)文件了。

您可試一下,這樣做肯定是沒(méi)有問(wèn)題的。

到此,問(wèn)題是被解決了,但是總覺(jué)得這樣的方式比較粗魯。

想一下:如果有很多的 .c 和 .h 文件呢,總不能手動(dòng)一個(gè)一個(gè)添加吧?

高級(jí)一點(diǎn)的方法

修改 Makefile 為下面這樣:

OBJS := main.o
TARGET := main
all : $(OBJS)
gcc -o $(TARGET) $(OBJS)
-include *.d
%.o: %.c
gcc $< -c -MMD -o $@

改動(dòng)部分有 2 處:

1. 添加了 -include *.d 指令;
2. gcc 編譯指令中,添加了 -MMD 參數(shù);

我們先執(zhí)行一下試試。第一次編譯:

$ ll      // 查看當(dāng)前文件
total 12
-rw-rw-r-- 1 root root  58 Jun  7 21:06 hello.h
-rw-rw-r-- 1 root root 122 Jun  7 20:51 main.c
-rw-rw-r-- 1 root root 119 Jun  7 21:05 Makefile

$ make    // 編譯
gcc main.c -c -MMD -o main.o
gcc -o main main.o

$ ll      // 再次查看當(dāng)前文件
total 32
-rw-rw-r-- 1 root root   58 Jun  7 21:06 hello.h
-rwxrwxr-x 1 root root 8608 Jun  7 21:06 main*
-rw-rw-r-- 1 root root  122 Jun  7 20:51 main.c
-rw-rw-r-- 1 root root   23 Jun  7 21:06 main.d
-rw-rw-r-- 1 root root 1528 Jun  7 21:06 main.o
-rw-rw-r-- 1 root root  119 Jun  7 21:05 Makefile

$ ./main  // 執(zhí)行
NUM = 1

有沒(méi)發(fā)現(xiàn):多出了一個(gè)文件 main.d,該文件內(nèi)容是:

main.o: main.c hello.h

這個(gè)文件正是因?yàn)?Makefile 中的 -MMD 這個(gè)參數(shù)導(dǎo)致生成的,而它的內(nèi)容正是我們需要的目標(biāo)文件依賴信息。

然后在 Makefile 中,include 這個(gè) .d 文件,從而讓 make 知道:main.o 文件依賴于 main.c 和 hello.o 這 2 個(gè)文件。

這個(gè)時(shí)候,我們?cè)賮?lái)修改 hello.h 中的內(nèi)容,例如:把 NUM 改成 10,再次編譯、執(zhí)行:

$ make
gcc main.c -c -MMD -o main.o
gcc -o main main.o

$ ./main
NUM = 10

Bingo,結(jié)果正確!



<上一頁(yè)  1  2  
聲明: 本文由入駐維科號(hào)的作者撰寫,觀點(diǎn)僅代表作者本人,不代表OFweek立場(chǎng)。如有侵權(quán)或其他問(wèn)題,請(qǐng)聯(lián)系舉報(bào)。

發(fā)表評(píng)論

0條評(píng)論,0人參與

請(qǐng)輸入評(píng)論內(nèi)容...

請(qǐng)輸入評(píng)論/評(píng)論長(zhǎng)度6~500個(gè)字

您提交的評(píng)論過(guò)于頻繁,請(qǐng)輸入驗(yàn)證碼繼續(xù)

  • 看不清,點(diǎn)擊換一張  刷新

暫無(wú)評(píng)論

暫無(wú)評(píng)論

    掃碼關(guān)注公眾號(hào)
    OFweek人工智能網(wǎng)
    獲取更多精彩內(nèi)容
    文章糾錯(cuò)
    x
    *文字標(biāo)題:
    *糾錯(cuò)內(nèi)容:
    聯(lián)系郵箱:
    *驗(yàn) 證 碼:

    粵公網(wǎng)安備 44030502002758號(hào)