[英]Is including header file necessary?
添加.h:
int add(int x, int y); // function prototype for add.h -- don't forget the semicolon!
为了在 main.cpp 中使用这个 header 文件,我们必须#include 它(使用引号,而不是尖括号)。
主.cpp:
#include <iostream>
#include "add.h" // Insert contents of add.h at this point. Note use of double quotes here.
int main()
{
std::cout << "The sum of 3 and 4 is " << add(3, 4) << '\n';
return 0;
}
添加.cpp:
#include "add.h"
int add(int x, int y)
{
return x + y;
}
嗨,我想知道,为什么我们在 add.cpp 文件中有 #include "add.h"? 我认为没有必要。
在 C++ 中,每个文件都在所谓的“翻译单元”中单独编译。 基本上在大多数设置中,翻译单元是单个.cpp 文件的编译。
当编译器编译 one.cpp 文件时,他看不到 other.cpp 文件中存储的信息。 它只看到这个 single.cpp 文件。
#include
是一个简单的文本替换指令。 #include "add.h"
告诉编译器将文件add.h
的内容(在编译器特定的包含搜索路径中找到)按原样插入到文件main.cpp
中。
当您编写add(3, 4)
时,编译器需要了解add
。 它返回什么? 是否需要unsigned long long
arguments 或unsigned char
arguments? 为了告诉编译器 function 返回类型和 arguments 类型,我们使用function 声明,例如int add(int, int);
. 或int add(int something, int anything);
. function 声明中的参数名称在这里用作程序员的文档 - 编译器的重要部分是类型。
编译器看不到add.cpp
中存储的信息。 它(通常)被编译为一个单独的翻译单元。 所以我们需要告诉编译器关于add()
function 周围的类型。 That information typically is stored in a header that is included in both translation units - in the "consumer" main.cpp
that uses the function and in the "implementation" add.cpp
that implements the function and what does it do. 通常,header 的名称与实现具有不同扩展名的函数的文件相同。
为什么我们在 add.cpp 文件中有 #include "add.h"?
主要是作为程序员对错误和更改的防御。 因为两个翻译单元是分开编译的,所以程序员的工作就是在它们之间正确地同步信息。
如果您要更改#include "add.h"
ex。 function add
的返回类型,但忘记在实现中更改它,编译器会抱怨。 当使用class
es 时,标题的使用变得越来越重要,它在 header 的一个地方定义了所有 class 成员、继承等。
为了“同步”接口和实现以减少错误,我们将 header 包含在消费者和实现中的声明中。 这样,如果您碰巧改变了前任。 function的返回类型,但是忘记更改add.cpp
文件,编译器会报错。
我认为没有必要。
对于这样一个简单的项目,没有必要,但如果你不这样做,我会认为它是“糟糕的风格”或“意大利面条代码”。 add.h
文件告诉我add.cpp
文件中有什么——它们定义了哪些函数。
为什么我们在 add.cpp 文件中有
#include "add.h"
add.cpp
" ? 我认为没有必要。
在这种情况下,不,没有必要,但也不是有害的。
像这样的一揽子样式规则有助于避免代码更改时可能出现的问题,尤其是在具有多个作者的大型项目中。
当然,没有必要。 但是,在实际项目中,具有更多功能,还是 class 声明。 它将成为强制性的。
所以,这是一个很好的做法,编译器需要一点时间来解析它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.