简体   繁体   English

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

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

Take this example: http://codebase.eu/tutorial/linux-socket-programming-c and http://codebase.eu/tutorial/linux-socket-programming-c/code/tcpclient.cpp 以以下示例为例: http : //codebase.eu/tutorial/linux-socket-programming-chttp://codebase.eu/tutorial/linux-socket-programming-c/code/tcpclient.cpp

Basically the first example app uses close() but does not include unistd.h. 基本上,第一个示例应用程序使用close(),但不包括unistd.h。 Some people mention this in the comments. 有人在评论中提到了这一点。 It works for some without it and others have to include it. 它适用于一些没有它的人,而其他人则必须包含它。

My question is why is this: Why is it sometimes not necessary? 我的问题是为什么:为什么有时没有必要? Is it better to include it always? 始终包含它是否更好? What does it mean when it is not necessary to include it? 不需要包含它是什么意思?

The referenced code uses <iostream> . 引用的代码使用<iostream> It is likely, that unistd.h gets included because of it. unistd.h可能因此而被包含在内。 But you should not count on it and include unistd.h yourself if you want to use close() . 但是,如果要使用close() ,则不要指望它,也不要自己包含unistd.h

It is always better to #include <unistd.h> when using int close(int); 使用int close(int);时最好包含#include <unistd.h> int close(int); because this is the only way to guarantee that a declaration of int close(int); 因为这是保证int close(int);的声明的唯一方法int close(int); will be available for your source code when compiling on POSIX platforms. 在POSIX平台上编译时,将可用于您的源代码。 In some cases other included files (or your buildchain) might include unistd.h or include a forward declaration for it. 在某些情况下,其他包含的文件(或您的构建链)可能包含unistd.h或包含对其的前向声明。

When the C++ preprocessor processes your source code, it basically replaces your #include <something.h> line with the preprocessed contents of something.h . 当C ++预处理器处理您的源代码时,它基本上将您的#include <something.h>行替换为something.h的预处理内容。 Hence if something.h (or recursively one of its included headers) has a #include <unistd.h> line then your source code will see the declaration of int close(int); 因此,如果something.h (或递归包含的头文件之一)具有#include <unistd.h>行,则您的源代码将看到int close(int);的声明int close(int); even thou you didn't directly include the unistd.h header. 即使您没有直接包含unistd.h标头也是如此。

However, to ensure portability, always include unistd.h if you use the int close(int); 但是,为确保可移植性,如果使用int close(int); ,请始终包含unistd.h int close(int); function ( man 3p close )! 功能( man 3p close )!

See this question if you want to find out where a header file might be included from. 如果要查找可能包含头文件的位置,请参阅此问题 Similarly you can use the -E flag for g++ / clang++ to output a fully preprocessed version of your source code to find out where the declaration of int close(int); 同样,您可以对g++ / clang++使用-E标志来输出源代码的完全预处理版本,以了解int close(int);的声明在哪里int close(int); comes from. 来自。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM