QQ_Sprite

导航

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 !

也没有问题。

 

 

posted on 2014-01-28 15:11  QQ_Sprite  阅读(5551)  评论(0编辑  收藏  举报