我读了这个答案: Must declare function prototype in 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]
基本上,C 似乎对我使用的每个系统调用函数都很生气。 我对 C 有点陌生,这对我来说似乎很奇怪,即使我知道我必须声明我编写的函数,我认为 C 会知道系统调用函数并且不需要我在代码中显式声明它们。
我需要做这样的事情吗:
int access(const char *pathname, int mode);
如果是这样,那为什么有意义?我使用其他语言,从不需要这样做。
最佳答案
是的,您应该为您进行的每个系统函数调用包含正确的 header 。您不会自己编写声明——您会弄错的。使用标题!
对于您引用的函数,相关的标题是:
#include <unistd.h> /* Many POSIX functions (but not all, by a large margin) */
#include <fcntl.h> /* open(), creat() - and fcntl() */
参见 POSIX 2008为其他 POSIX 函数找到正确的 header 。
C99 标准要求所有函数在使用前声明或定义。
对于您自己的功能,您应该模仿“系统”。将有一个声明该函数的头文件、实现它的源文件以及使用该函数的其他源文件。其他源文件使用 header 来获得正确的声明。实现文件包含 header 以确保其实现与其他源文件所期望的一致。所以 header 是将它们粘合在一起的粘合剂。
关于c - 我应该在 C 中声明系统调用函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13405058/