将代码文本编译为机器能识别的二进制指令。
预处理、编译、汇编、链接
汇编。
编译。
因为函数链接定位在链接的阶段,而不是在编译阶段。
==================1.gcc编译流程==========================
指令:gcc hello.c -o hello.i -E
作用:处理所有的预处理指令(以#开头,比如头文件包含、宏定义、条件编译)
指令:gcc hello.i -o hello.s -S
作用:词法、语法分析,根据平台生成最接近机器的语言(汇编)。
指令:gcc hello.s -o hello.o –c
作用:将汇编指令文件翻译为可直接运行的二进制指令流。
指令:gcc hello.o -o hello –lc -lgcc
作用:重定位(函数和全局变量等)、链接库、合并段
备注:
================== 2.预处理指令 ==========================
在源码中,以#开头的语句,称为预处理指令,他们不属于C语言语法。
#define PI 3.1415926 // 预处理阶段中,将代码中所有宏进行替换。
#if #ifdef #ifndef #elif #else #endif
#include <stdio.h>
备注:
可添加一些调试语句,通过编译指令去控制调试语句的输出。
gcc demo4_条件编译ifdef-ifndef.c -o demo –DTEST
demo1_编译过程
#include <stdio.h>
#include <string.h>
void hahaha(char *str);
int main()
{
printf("hello world.\n");
hahaha("hello world.\n");
return 0;
}
demo2_define宏定义
#include <stdio.h>
#include <string.h>
// 不带参宏
// #define PI
#define PI 3.1415926 // 预处理阶段中,将代码中所有宏进行替换。
// 带参宏(宏函数)
#define SUM(a,b) (a+b)
// 子函数
float func_sum(float a, float b);
int main()
{
printf("hello world.\n");
float r = 5.0;
printf("面积: %f\n", PI*r*r);
printf("周长: %f\n", 2*PI*r);
float var1 = 1.2;
float sum = func_sum(r, var1)*2;
printf("sum: %f\n", sum);
sum = SUM(r, var1)*2;
printf("sum: %f\n", sum);
return 0;
}
float func_sum(float a, float b)
{
return a+b;
}
demo3_条件编译_if-else
#include <stdio.h>
#include <string.h>
int main()
{
#if 0
printf("hello world.\n");
printf("hello world.\n");
printf("hello world.\n");
printf("hello world.\n");
printf("hello world.\n");
printf("hello world.\n");
#else
printf("nihao 123.\n");
printf("nihao 123.\n");
printf("nihao 123.\n");
printf("nihao 123.\n");
printf("nihao 123.\n");
printf("nihao 123.\n");
#endif
return 0;
}
demo4_条件编译ifdef-ifndef
#include <stdio.h>
#include <string.h>
int main()
{
#ifdef TEST
printf("[%d]\n", __LINE__);
#endif
printf("nihao 123.\n");
printf("nihao 123.\n");
printf("nihao 123.\n");
printf("nihao 123.\n");
printf("nihao 123.\n");
printf("nihao 123.\n");
#ifdef TEST
printf("[%d]\n", __LINE__);
#endif
return 0;
}
demo5_使用自己的头文件
#include <stdio.h>
#include <string.h>
// 包含系统头文件
#include "myhead.h"
#include "myhead.h"
#include "myhead.h"
#include "myhead.h"
#include "myhead.h"
#include "myhead.h"
#include "myhead.h"
#include "myhead.h"
#include "myhead.h"
#include "myhead.h"
// 包含自定义头文件
int main()
{
printf("%d\n", ABC);
return 0;
}
myhead.h
#ifndef _MYHEAD_H
#define _MYHEAD_H
#define ABC 1234
#endif