C语言的编译过程
预处理
- 把
include、define
引入或者定义的东西替换一下。
# cpp -o ***.i ***.c
gcc -E
编译
- 编译成汇编语言
# cc1 -o ***.s ***.c
gcc -S
汇编
# as -o ***.o ***.s
gcc -c
链接
# collect2 -o *** ***.o+...
gcc -o
C语言常见错误
预处理错误
#include “name”
:查找系统目录及当前目录#include <name>
: 只查找系统目录
如果头文件不在系统目录和当前目录,则会出现not find
的错误信息。
- 解决方案:
gcc -I
跟查找头文件的目录
编译错误
- 语法错误:缺少; {}之类的
链接错误
undefined reference to `***(function)`
:寻找标签(函数)是否实现了,链接时是否一起链接。multiple definition of `***(function)`
:多次实现了标签(函数),重复。
预处理内容
包含头文件
#include
宏
#define
宏名 宏体。预处理宏的时候不进行语法检查。- 宏参数:
#define A(x) (2+(x))
条件预处理
#ifdef #else #endif
//test.c
_______________________________________________________
#include <stdio.h>
int main(){
#ifdef DEBUG
printf("%s \n", __FILE__);
#endif
printf("hello world!\n");
return 0;
}
_______________________________________________________
gcc -DDEBUG -o test test.c
./test
output:
test.c
hello world!
gcc -o test test.c
./test
output:
hello world!
预定义宏
__FUNCTION__
:函数名
__LINE__
:行号
__FILE__
:文件名
//test.c
_______________________________________________________
#include <stdio.h>
int main(){
printf("%s %s %d", __FUNCTION__, __FILE__, __LINE__);
return 0;
}
_______________________________________________________
output: main test.c 3
//test.c
_______________________________________________________
#include <stdio.h>
int fun(){
printf("%s %s %d", __FUNCTION__, __FILE__, __LINE__);
return 0;
}
int main(){
fun();
return 0;
}
_______________________________________________________
output: fun test.c 3
宏展开下的#、##
- #:字符串
- ##:连接符
#include "stdio.h"
#define A(x) #x
#define DAY(x) day##x
int main(){
int day1=10;
int day2=20;
printf(A(abc\n));
printf("day is %d\n", DAY(1));
return 0;
}
________________________________________________________
output:
abc
day is 10