我应该在C中声明系统调用函数吗?

pep*_*dip 4 c linux declaration function system-calls

我读到了这个答案: 必须在C中声明函数原型吗?

我的问题更具体:

在使用系统中的程序调用一样access(),open(),creat(),write(),read()...我必须声明每个系统调用函数?这是C的工作方式吗?因为我得到以下内容:

hw1.c: In function ‘main’:
hw1.c:50:9: warning: implicit declaration of function ‘access’ [-Wimplicit-function-declaration]
hw1.c:131:9: warning: implicit declaration of function ‘lseek’ [-Wimplicit-function-declaration]
hw1.c: In function ‘writeFile’:
hw1.c:159:17: warning: implicit declaration of function ‘write’ [-Wimplicit-function-declaration]
Run Code Online (Sandbox Code Playgroud)

基本上,似乎C对我正在使用的每个系统调用函数都很生气.我对C有点新鲜,虽然我知道我必须声明我编写的函数,但我觉得C会知道系统调用函数并且不需要我在代码中明确声明它们.

我需要做这样的事情:

int access(const char *pathname, int mode);

如果是这样,为什么这有意义呢?我使用其他语言,从来没有必要这样做.

Jon*_*ler 11

是的,您应该为每个系统函数调用包含正确的标头.你自己不写声明 - 你会弄错它们.使用标题!

对于您引用的功能,相关标头是:

#include <unistd.h>  /* Many POSIX functions (but not all, by a large margin) */
#include <fcntl.h>   /* open(), creat() - and fcntl() */
Run Code Online (Sandbox Code Playgroud)

请参阅POSIX 2008以查找其他POSIX函数的正确标头.

C99标准要求在使用之前声明或定义所有函数.


对于您自己的功能,您应该模拟"系统".将有一个声明该函数的头,实现它的源文件以及使用该函数的其他源文件.其他源文件使用标头来获取正确的声明.实现文件包含标头,以确保其实现与其他源文件所期望的一致.所以标题是将它们组合在一起的粘合剂.