Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1717949
  • 博文数量: 410
  • 博客积分: 9563
  • 博客等级: 中将
  • 技术积分: 4517
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-03 19:59
个人简介

文章分类

全部博文(410)

文章存档

2017年(6)

2016年(1)

2015年(3)

2014年(4)

2013年(32)

2012年(45)

2011年(179)

2010年(140)

分类: C/C++

2010-07-03 20:06:46

一直都希望能够把make弄得清晰些,今天就从最简单的开始

例子1:(hello.c)
C语言:
1 #include
2 int main(int argc, char** argv)
3 {
4     printf("Hello, Linux World!\n");
5     return 0;
6 }
简单的都不用make了,编译命令是
gcc -Wall hello -o hello
还是弄个make文件试试吧
Makefile语言:
hello: hello.c
    gcc -Wall hello.c -o hello
在当前目录下运行make,生成了hello运行文件

例子2:(hello.c hello.h)
现在来加个头文件hello.h,先把hello.c改成这个样子(为了方便检验hello.h是否修改,我加了一个变量)
C语言
:
1 #include "hello.h"
2 int main(int argc, char** argv)
3 {
4     printf("Hello, Linux World! \nnow:%d\n",a);
5     return 0;
6 }
建立一个hello.h,内容如下:
C语言:
1 #include
2 int a=100;
运行编译命令(运行make效果一样)
gcc -Wall hello.c -o hello
编译器会自动找到当前目录下的头文件(hello.h),运行命令
./hello
输出
Hello, Linux World!
now:100
现在修改hello.h中的a变量的值到200
1 #include
2 int a=200;
运行命令
./hello
输出
Hello, Linux World!
now:100

看样子a变量值修改没有效果,再用make试验一下,提示
make: “hello”是最新的。
运行编译命令
gcc -Wall hello.c -o hello
./hello
输出
Hello, Linux World!
now:200
这次gcc和make调用gcc结果不同了,把make文件改一下(在第一行加hello.h,告诉gcc如果hello.h修改了重新编译)
Makefile语言:
1 hello: hello.c hello.h
2     gcc -Wall hello.c -o hello
现在把a=200改成300,结果make 和直接gcc效果一样了

例子3:(src/hello.c include/hello.h makefile)
现在来个带目录的例子,一般我们都是把源文件和头文件放到不同的目录里面,把各个文件按照下面的目录结构移动过去
mkdir src
mkdir include
mv hello.c ./src/
mv hello.h ./include/
结果变成这个样子
|---makefile
|---src
|    |---hello.c
|---include
|      |---hello.h
现在make会报告错误
make: *** 没有规则可以创建“hello”需要的目标“hello.c”。 停止。
把make文件修改成这样,利用VPATH变量来指定搜索目录(参考这个帖子
VPATH只是告诉了Make在哪里寻找文件, 而gcc并不知道在哪里寻找hello.h (即VPATH只和Makefile中的target, prerequisites相关, 而不和command相关). 所以gcc 要加-I include 参数
Makefile语言:
1 VPATH = src include
2 hello: hello.c hello.h
3     gcc -I include -Wall $< -o hello
利用vpath更加灵活
Makefile语言:
1 vpath %.h include
2 vpath %.c src
3 hello: hello.c hello.h
4     gcc -I include -Wall $< -o hello
也可以声明一个CFLAGS变量,把路径设置放在make文件的头部.
Makefile语言:
1 vpath %.h include
2 vpath %.c src
3 CFLAGS = -I include
4
5 hello: hello.c hello.h
6     gcc $(CFLAGS) -Wall $< -o hello

如果希望每次make都能自动运行hello,可以这样写make文件
Makefile语言:
01 vpath %.h include
02 vpath %.c src
03 CFLAGS = -I include
04 all: hello run
05 .PHONY: all
06
07 hello: hello.c hello.h
08     gcc $(CFLAGS) -Wall $< -o hello
09 run:
10     ./hello


阅读(1278) | 评论(1) | 转发(0) |
0

上一篇:心情

下一篇:make 文件入门(二)

给主人留下些什么吧!~~

keithrichars2014-01-14 12:12:25

还不错