Makefile 一點一滴(二)—— 輸出文件到指定路徑


先來看最簡單的 makefile 文件:

TestCpp : TestCpp.o
    g++ -o TestCpp TestCpp.o

TestCpp.o : TestCpp.cpp
    g++ -c TestCpp.cpp
    
clean : 
    rm -rf TestCpp.o

冒號前是要生成的文件,冒號后是該文件所依賴的文件

下一行是生成所需的文件,注意,一定要以Tab開頭。

 

這里,我想將可執行文件置入 ./bin 路徑下,二進制 .o 文件置入 ./debug 路徑下,源文件 .cpp 置入 ./src 路徑下

於是我將其修改為:

 

TestCpp : ./debug/TestCpp.o
    g++ -o TestCpp ./debug/TestCpp.o

./debug/TestCpp.o : ./src/TestCpp.cpp
    g++ -c ./src/TestCpp.cpp
    
clean : 
    rm -rf ./debug/TestCpp.o

,創建好 bin、src、debug 文件夾,重新執行 make,輸出:

[@localhost TestCpp]$ ls
bin  debug  makefile  src
[@localhost TestCpp]$ make
g++ -c ./src/TestCpp.cpp
g++ -o TestCpp ./debug/TestCpp.o
g++: ./debug/TestCpp.o
g++: make: *** [TestCpp]  1

make失敗,於是我僅make .o:

[@localhost TestCpp]$ make ./debug/TestCpp.o
g++ -c ./src/TestCpp.cpp
[@localhost TestCpp]$ ls
bin  debug  makefile  src  TestCpp.o
[@localhost TestCpp]$ 

生成 TestCpp.o 成功了,但是卻不是在我指定的目錄 debug/ 下。

證明 :

./debug/TestCpp.o : ./src/TestCpp.cpp
    g++ -c ./src/TestCpp.cpp

這句寫的是對的。

 

在這個地方上困擾了很久,最后才發現,我沒有為 .o 指定輸出路徑,

“ g++ -c ./src/TestCpp.cpp ” 找不到輸出.o的路徑,正確的寫法是:

“ g++ -c -o ./debug/TestCpp.o ./src/TestCpp.cpp ”

 

修改makefile

 【makefile —— 第二個版本】

TestCpp : ./debug/TestCpp.o
    g++ -o TestCpp ./debug/TestCpp.o

./debug/TestCpp.o : ./src/TestCpp.cpp
#    g++ -c ./src/TestCpp.cpp
    g++ -c -o ./debug/TestCpp.o ./src/TestCpp.cpp
    
clean : 
    rm -rf ./debug/TestCpp.o

 

並重新執行 make,輸出:

 

[@localhost TestCpp]$ make
g++ -c -o ./debug/TestCpp.o ./src/TestCpp.cpp
g++ -o TestCpp ./debug/TestCpp.o
[@localhost TestCpp]$ ls
bin  debug  makefile  src  TestCpp
[@localhost TestCpp]$ ls debug/
TestCpp.o

 

我們發現,這次輸出是對的。執行 ./TestCpp,輸出:

[@localhost TestCpp]$ ./TestCpp 
Hello C++ Language !

也沒有問題。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM