原文地址:http://blog.csdn.net/stpeace/article/details/53054679
目录下有test1.cpp, test2.cpp, test3.cpp三个独立文件(彼此之间并无依赖与调用关系), 要编译成三个可执行程序, 怎么搞呢? 我们看看makefile:
- test1: test1.cpp
- test2: test2.cpp
- test3: test3.cpp
- clean:
- rm -f test1 test2 test3
- taoge@localhost Desktop> make
- g++ test1.cpp -o test1
- taoge@localhost Desktop>
那改一下:
- test1 test2 test3: test1.cpp test2.cpp test3.cpp
- clean:
- rm -f test1 test2 test3
- taoge@localhost Desktop> make
- g++ test1.cpp test2.cpp test3.cpp -o test1
- /tmp/ccAX6NNB.o: In function `main':
- test2.cpp:(.text+0x72): multiple definition of `main'
- /tmp/ccaITY1Z.o:test1.cpp:(.text+0x72): first defined here
- /tmp/cc4Wsk9m.o: In function `main':
- test3.cpp:(.text+0x72): multiple definition of `main'
- /tmp/ccaITY1Z.o:test1.cpp:(.text+0x72): first defined here
- collect2: ld returned 1 exit status
- make: *** [test1] Error 1
- taoge@localhost Desktop>
那怎么办? 我们反思一下上面的两次失败:
在前一次中, 我们其实只定义了一个target文件(因cpp独立), 也就是test1.
在后一次中, 我们定义了三个target文件, 可是, 杂糅链接了(依赖关系杂糅)。
那好, 我们来改进一下, 兼顾到上面两种情况:
- all: test1 test2 test3
- test1: test1.cpp
- test2: test2.cpp
- test3: test3.cpp
- clean:
- rm -f test1 test2 test3
- taoge@localhost Desktop> make clean
- rm -f test1 test2 test3
- taoge@localhost Desktop> make all
- g++ test1.cpp -o test1
- g++ test2.cpp -o test2
- g++ test3.cpp -o test3
- taoge@localhost Desktop> ls
- makefile test1 test1.cpp test2 test2.cpp test3 test3.cpp
- taoge@localhost Desktop>
这里有个疑问, 为什么没有生成all文件呢? 因为all下面并没有待执行的命令,也无法自动推导。 我们来看看改动的makefile:
- all: test1 test2 test3
- @echo testing
- test1: test1.cpp
- test2: test2.cpp
- test3: test3.cpp
- clean:
- rm -f test1 test2 test3
- taoge@localhost Desktop> make all
- g++ test1.cpp -o test1
- g++ test2.cpp -o test2
- g++ test3.cpp -o test3
- testing
- taoge@localhost Desktop>
以上部分应该比较好动, 现在还有个问题, 如果有100个cpp文件, 那该怎么搞起呢? 写到test100? 麻烦死了, 明显不符合计算机的思维, 好, 那就搞个模式规则吧, 如下:
- all: test1 test2 test3
- %:%.cpp
- g++ $ make clean
- rm -f test1 test2 test3
- taoge@localhost Desktop> make all
- g++ test1.cpp -o test1
- g++ test2.cpp -o test2
- g++ test3.cpp -o test3
- taoge@localhost Desktop>
- %:%.cpp
- g++ $
本文所谓的模式规则, 其实就是:
- %:%.cpp
- g++ $
关注打赏
最近更新
- 深拷贝和浅拷贝的区别(重点)
- 【Vue】走进Vue框架世界
- 【云服务器】项目部署—搭建网站—vue电商后台管理系统
- 【React介绍】 一文带你深入React
- 【React】React组件实例的三大属性之state,props,refs(你学废了吗)
- 【脚手架VueCLI】从零开始,创建一个VUE项目
- 【React】深入理解React组件生命周期----图文详解(含代码)
- 【React】DOM的Diffing算法是什么?以及DOM中key的作用----经典面试题
- 【React】1_使用React脚手架创建项目步骤--------详解(含项目结构说明)
- 【React】2_如何使用react脚手架写一个简单的页面?
立即登录/注册


微信扫码登录