C/C++的头文件分开写法和在gcc/g++、cmake、VSCode上运行结果

8 篇文章 0 订阅


总结:

  • 头文件只有xxx.h(声明和实现在一起):
    那么gcc/g++、Cmake、VSCode都可以运行
  • 头文件分为xxx.hxxx.cpp(声明和实现分开):
    那么只能在gcc/g++、Cmake下运行(推荐Cmake),VSCode报错。

后者分开实现的方式是很多人的写法(github),看来大家都用cmake
PS:我在VSCode下用终端
点下面栏的那个TERMINAL

在这里插入图片描述


一、简单的头文件:声明和实现写在一起

1.实现

c和c++一样,这里拿c++举例。

程序共两个文件:

  • main.cpp:main()函数入口
  • hello.h:头文件中直接包含函数定义。PS:自定义头文件得用#Include "header_name"
  1. 创建hello.h
gedit hello.h
void hello()
{
	cout<<"hello.h"<<endl;
}
  1. 创建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::coutstd::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
  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值