在这记录一下学习笔记,学习来源一般都是看书或者网上百度,都是些基础知识(有很多是csdn其他作者写的文章,感谢,但因为看的很杂就很难一一标注出来了)
Makefile基础
一、基本规则
规则
Makefile由一组规则(Rule)组成,每条规则的格式是:
target ... : prerequisites ...
command1
command2
target:目标;
prerequisites:条件;
command1、command2:命令列表;
1、目标和条件之间的关系是:欲更新目标,必须首先更新它的所有条件;所 有条件中只要有一个条件被更新了,目标也必须随之被更新。所谓“更新”就是执行一遍规则中的命令列表。
2、命令列表中的每条命令必须以一个Tab开头,对于Makefile中的每个以Tab开头的命令,make会创建一个Shell进程去执行它。
3、第一条规则的目标称为缺省目标,只要缺省目标更新了就算完成任务了,其它工作都是为这个目的而做的。
eg:
代码:
main.cpp
#include <stdio.h>
#include "my_printf.h"
int main()
{
my_printf("hello world\n");
return 0;
}
my_printf.cpp
#include <stdio.h>
#include "my_printf.h"
int my_printf(const char * pPrintfInfo)
{
if(pPrintfInfo == NULL)
{
return -1;
}
printf("%s\n", pPrintfInfo);
return 0;
}
my_printf.h
#ifndef _MY_PRINTF_HEADER_
#define _MY_PRINTF_HEADER_
int my_printf(const char *pPrintfInfo);
#endif
Makefile文件
main: main.o my_printf.o
g++ main.o my_printf.o -o main
main.o: main.cpp my_pritnf.h
g++ -c main.cpp
my_printf.o: my_printf.cpp my_printf.h
g++ -c my_printf.cpp
make执行步骤:
1、尝试更新缺省目标,无缺省目标或缺省目标的条件有任意一个被更新,则需要更新目标即main。按照更新目标必须先更新条件:即main.o和my_printf.o。
2、make进一步查找以这两个条件为目标的规则(第二第三条规则),按照目标更新规则(基本规则第一条),这两个目标也需要更新,于是分别执行相应规则的命令列表去跟新相应的目标。
3、两个缺省目标更新后make执行缺省目标的命令列表去更新缺省目标,至此make完成执行任务。
注:gcc/g++编译步骤及命令
1、预处理:
主要作用是加载头文件、宏替换、条件编译的作用,.i文件是预处理后生成的预编译文件(还是c文件)。
命令:gcc -E hello.c -o hello.i
2、编译:
进行代码的规范性检查以及代码是否有语法错误,.s文件为编译阶段生成的汇编文件(汇编文件)。
命令:gcc -S hello.i -o hello.s
3、汇编:
将汇编文件转换成二进制文件,生成.o文件(二进制文件)。
命令:gcc -c hello.s -o hello.p
4、连接:
连接所需要的函数库,将二进制文件连接成一个可执行文件(可执行文件)。
命令:gcc hello.o -o hello