Skip to Content
C++程序设计:原理与实践(基础篇)(原书第2版)
book

C++程序设计:原理与实践(基础篇)(原书第2版)

by 本贾尼 斯特劳斯特鲁普
August 2021
Intermediate to advanced
450 pages
9h 36m
Chinese
Pearson
Content preview from C++程序设计:原理与实践(基础篇)(原书第2版)

8.3 头文件

我们如何管理声明和定义呢?这是一个大问题,因为声明和定义要一致,而实际程序可能会有数万个声明,甚至几十万个也不罕见。一般地,当我们编写程序时,我们使用的定义多数都不是我们自己写的。例如,cout和sqrt()的实现就是别人在很多年前写的,我们只是使用它们。

在C++中,对于“别处”定义的功能的声明,管理它们的关键是“头部”。本质上,一个头部(header)是一些声明的集合,一般定义于一个文件,因此也称为头文件(header file)。这样的头文件随后用#include包含在我们的源文件中。例如,我们可能决定改进计算器程序(第6章和第7章)的源码组织,将单词管理部分分隔出去。我们可以定义一个包含Token类和Token_stream类的声明的头文件token.h:

Token和Token_stream的声明在头文件token.h中,而它们的定义在token.cpp中。后缀.h通常用于C++头文件,而.cpp后缀通常用于C++源文件。实际上,C++语言并不关心文件后缀,但一些编译器和很多程序开发环境坚持这种命名习惯,因此你的源码组织也请遵循这一惯例。

原则上,#include"file.h"只是简单地将file.h中的声明复制到你的文件中#include指令处。例如,我们可以写一个头文件f.h:

并将它包含于我们的源文件user.cpp中:

当编译user.cpp时,编译器会执行包含操作,然后编译得到的如下程序

由于#include的处理逻辑上在编译器任何其他动作之前进行,因此被称为预处理(preprocessing)(A.17节)。 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

C++语言导学(原书第2版)

C++语言导学(原书第2版)

本贾尼 斯特劳斯特鲁普
管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey
Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano

Publisher Resources

ISBN: 9787111562252