使用Makefile
来自软件实验室
目录
函数的概念
函数的四个基本要素:名称、返回值、参数、函数体
库函数
- 标准库函数,http://net.pku.edu.cn/~yhf/linux_c/ , /usr/include
- 第三方库函数
- 内核函数库:《Unix环境高级编程》
- 用户自定义函数
空函数的意义
构建程序的outline,像写文章那样写程序:
#include "stdio.h" void insert_card(){ } void verify_card_number(){} void verify_password(){} void authenticate_user(){ verify_card_number(); verify_password(); } void input_number(){ } void verify_money(){ } void close(){ } void main(){ insert_card(); authenticate_user(); input_number(); verify_money(); close(); }
多文件C语言源代码的组织和编译
通常将相关功能的函数组织在一个文件中形成属于项目的函数库,每个文件gcc -c编译为独立的.o目标文件,最后统一链接生成可执行文件。
file1.c:
#include "stdio.h" void main(){ int a; printf("please input the number:\n"); scanf("%d",&a); printf("square(a)=%d\n",square(a)); }
file22.c:
#include "stdio.h" int square(int x) { return x*x; }
执行如下的命令:
gcc -c file1.c gcc -c file2.c gcc file1.o file2.o -o file12
Makefile
基本的Makefile文件
上面多文件C语言源代码的例子的Makefile文件:
file12:file1.o file2.o gcc file1.o file2.o -o file12 file1.o:file1.c gcc -c file1.c file2.o:file2.c gcc -c file2.c clean: rm file1.o file2.o
注意几个问题:
- 默认目标是哪个?
- 命令前面的空格
- 理解make的递归调用原则
变量
- 变量的定义和引用:和shell类似
- 自动变量和预定义变量,类似于shell的位置变量和预定义的环境变量
隐式规则
即make可以根据目标自动推导依赖(惯例),比如上面的Makefile文件可以简化为:
file12:file1.o file2.o gcc file1.o file2.o -o file12 clean: rm file1.o file2.o
或者更“合理”一些的写法:
OBJS=file1.o file2.o file12: gcc $(OBJS) -o file12 clean: rm file12 $(OBJS)
makefile的教程
- make的官方介绍: https://www.gnu.org/software/make/manual/html_node/index.html
- http://wiki.ubuntu.org.cn/%E8%B7%9F%E6%88%91%E4%B8%80%E8%B5%B7%E5%86%99Makefile
- http://www.chinaunix.net/old_jh/23/408225.html
autoconf
安装:apt-get install automake
基本流程
项目的目录结构:
|-- conf | `-- test.conf `-- src |-- file1.c `-- file2.c
- autoscan,生成configure.scan
- mv configure.scan configure.ac编辑configure.ac如下:
# -*- Autoconf -*- # Process this file with autoconf to produce a configure script. AC_PREREQ([2.69]) AC_INIT(hello, 1.0) AM_INIT_AUTOMAKE # Checks for programs. AC_PROG_CC # Checks for libraries. # Checks for header files. # Checks for typedefs, structures, and compiler characteristics. # Checks for library functions. AC_OUTPUT(Makefile src/Makefile)
- 执行aclocal,autoconf
- 编辑Makefile.am如下:
SUBDIRS=src
- 编辑src/Makefile.am如下:
bin_PROGRAMS=hello hello_SOURCES=file1.c file2.c
- 编辑conf/Makefile.am:
testconfig=/etc test_DATA=test.conf
- touch README NEWS AUTHORS ChangeLog
- automake --add-missing
- ./configure,生成了Makefile !
- make