为什么有些代码文件使用 close() 而不包含 unistd.h
Why do some code files use close() without including unistd.h?
举这个例子: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
。
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 编译包含字符串的代码时遇到问题
- c++库的公共头文件中应该包含什么
- 将包含C样式数组的对象初始化为成员变量(C++)
- 是否需要删除包含对象的"pair"?
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 使用mongocxx驱动程序时包含头文件问题
- 如何在h文件中包含.o对象文件
- 在混合代码库中将C转换为C++时出现许多包含错误
- VS2017,C++包含目录与附加包含目录,子文件夹包含失败-但为什么
- cmath抛出错误C2062、C2059、C2143和C2447.cmath包含在矢量文件中
- 为什么您需要C++头文件的包含保护
- 无法在UE4中包含BP类到CPP类
- g++ 说函数不存在,即使包含正确的标头
- 在C++代码中包含opencv时,使用ctypes创建.so文件
- 为什么有些代码文件使用 close() 而不包含 unistd.h
- 如果包含<unistd.h>C++奇怪的编译器错误
- 无法打开包含文件:"unistd.h":没有这样的文件或目录