之前学c的时候就一直没搞明白头文件的作用,稀里糊涂的
今天给好好捋一下,打打基础
首先要明确c语言的编译过程:直达精析
预处理中, 展开头文件/宏替换/去掉注释/条件编译
头文件就用在这
头文件通常用来定义 数据类型,声明变量、函数、结构和类
由于c语言有着先定义后使用的规则当你要调用其它源文件中的函数、类等用于当前源文件中,就必须在当前源文件最前面给出声明
另一种更直接的说法就是
将#include "a.h"直接换成a.h文件内的内容
来实例:
main.cpp
#include <iostream>
#include "a.h"
using namespace std;
int main()
{
cout<<"this is main"<<endl;
a_fun();
}
a.cpp
#include<iostream>
using namespace std;
void a_fun()
{
cout<<"this is a function";
}
a.h
#ifndef A_H
#define A_H
void a_fun();
#endif
CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 2.8) #最低版本要求
project(csdn) #项目名称
add_executable(main main.cpp a.cpp ) #指定生成目标
结果:
好,现在不用头文件,将其直接替换掉,如下:
#include <iostream>
// #include "a.h"
void a_fun();
using namespace std;
int main()
{
cout<<"this is main"<<endl;
a_fun();
return 0;
}
重新编译,运行结果不变
还有头文件和源文件之间没有必然联系,大家只是为了方便才将a.cpp 的头文件命名为a.h ,如果你愿意只要里面的内容不变(内容就是对a.cpp中的函数等等的声明)完全可以命名为b.h 、c.h …,对应的在调用的时候换成b.h 、c.h就行了
#include <iostream>
#include "b.h"
using namespace std;
int main()
{
cout<<"this is main"<<endl;
a_fun();
return 0;
}
#ifndef xx
#define xx
#endif 是用来防止重定义的
xx是可以随意定的
书写规范