文章目录
总结:
-
头文件只有
xxx.h
(声明和实现在一起):
那么gcc/g++、Cmake、VSCode都可以运行 -
头文件分为
xxx.h
,
xxx.cpp
(声明和实现分开):
那么只能在gcc/g++、
Cmake
下运行(推荐Cmake),VSCode报错。
后者分开实现的方式是很多人的写法(github),看来大家都用cmake
PS:我在VSCode下用终端
点下面栏的那个TERMINAL
一、简单的头文件:声明和实现写在一起
1.实现
c和c++一样,这里拿c++举例。
程序共两个文件:
-
main.cpp:
main()
函数入口 -
hello.h:头文件中直接包含函数定义。PS:自定义头文件得用
#Include "header_name"
。
- 创建hello.h
gedit hello.h
void hello()
{
cout<<"hello.h"<<endl;
}
- 创建main.cpp
gedit main.cpp
#include<iostream>
using namespace std;
#include"hello.h"
int main()
{
hello();
cout<<"main.cpp"<<endl;
return 0;
}
2.头文件的理解
注意
main.cpp
中
#include<hello.h>
是声明在
using namespace std
之后的,如果声明在之前,那么就会报错:cout和endl未声明。(当然你在
hello.h
中再写一遍
using namesapce std
也可以,或者使用
std::cout
和
std::endl
)
这是因为
头文件其实是替换
:
#include<iostream>
using namespace std;
void hello()
{
cout<<"hello.h"<<endl;
}
int main()
{
hello();
cout<<"main.cpp"<<endl;
return 0;
}
这样自然就解释了为什么会有顺序。
3.用什么编译执行都ok
(1)gcc/g++
g++执行的时候只用执行
main.cpp
就行:
g++ main.cpp
./a.out
打上
hello.h
反而出错
g++ main.cpp hello.h
报错:
hello.h: In function ‘void hello()’:
hello.h:3:2: error: ‘cout’ was not declared in this scope
cout<<"hello.h"<<endl;
^
hello.h:3:19: error: ‘endl’ was not declared in this scope
cout<<"hello.h"<<endl;
(2)VSCode
莫得问题
(3)Cmake
当前文件内容:
建立CMakeLists.txt:
gedit CMakeLists.txt
新建CMakeLists.txt文件内容:
PROJECT(HelloProject)
AUX_SOURCE_DIRECTORY(. SRC_LIST)
ADD_EXECUTABLE(hello ${SRC_LIST})
编译执行:
mkdir build
cd build
cmake ..
make
./hello
结果莫得问题。
二、工程式头文件:声明和实现分开
1.实现
程序共两个文件:
-
main.cpp:
main()
函数入口 - hello.h:头文件中只包含函数声明。
- hello.cpp:头文件中是函数实现
/*hello.h*/
#ifndef CIRCLE_H
#define CIRCLE_H
void hello();
#endif
/*hello.cpp*/
#include"hello.h" // 注意hello.cpp中包含hello.h
#include<iostream>
using namespace std;
void hello()
{
cout<<"hello.cpp"<<endl;
}
/*main.cpp*/
#include<iostream> // 注意main.cpp中包含hello.h
#include"hello.h"
using namespace std;
int main()
{
hello();
cout<<"main.cpp"<<endl;
return 0;
}
#ifndef
、
#endif
是为了保证不会多次编译同一个文件而重复定义导致错误:
预编译命令之#define、#if、#ifdef、#ifndef、#undef
2.编译执行
(1)gcc/g++
这里就不同与【一、】了,我们需要编译
hello.cpp
了。
g++ main.cpp hello.cpp
./a.out
(2)Cmake
同上,结果ok
(3)VScode
报错,猜测是因为配置问题,我们其实还是只编译了
main.cpp
,但不知道怎么修改配置。
undefined reference to `hello()'
collect2: error: ld returned 1 exit status
The terminal process terminated with exit code: 1