为什么有些代码文件使用 close() 而不包含 unistd.h

Why do some code files use close() without including unistd.h?

本文关键字:包含 unistd close 代码 文件 为什么      更新时间:2023-10-16

举这个例子:http://codebase.eu/tutorial/linux-socket-programming-c 和http://codebase.eu/tutorial/linux-socket-programming-c/code/tcpclient.cpp

基本上,第一个示例应用程序使用 close((,但不包括 unistd.h。有些人在评论中提到了这一点。它适用于一些没有它的人,而其他人必须包含它。

我的问题是为什么会这样:为什么有时没有必要?总是包含它更好吗?当没有必要包含它时,这意味着什么?

使用 int close(int); 时最好#include <unistd.h>,因为这是保证在 POSIX 平台上编译时源代码可以使用int close(int);声明的唯一方法。在某些情况下,其他包含的文件(或构建链(可能包含unistd.h或包含它的前向声明。

当C++预处理器处理您的源代码时,它基本上会用something.h的预处理内容替换您的#include <something.h>行。因此,如果something.h(或递归地包含的标头之一(具有#include <unistd.h>行,那么您的源代码将看到int close(int);声明,即使您没有直接包含unistd.h标头。

但是,为了确保便携性,如果您使用int close(int);功能(man 3p close(,请始终包括unistd.h

如果要了解头文件可能包含在何处,请参阅此问题。同样,您可以使用 g++/clang++-E 标志来输出源代码的完全预处理版本,以找出int close(int);声明的来源。

引用的代码使用 <iostream> .很可能,unistd.h因此而被包括在内。但是,如果您想使用close(),则不应指望它并包括自己unistd.h