Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I declare system call functions in C?

I read this answer: Must declare function prototype in C?

My question is more specific:

In a program that uses system calls like access(), open(), creat(), write(), read()... Must I declare every system call function? Is that how C works? Because I'm getting the following:

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]

Basically, it seems C is angry with every system call function I'm using. I am somewhat new to C and this appears strange to me even though I know I have to declare functions I write I would think C would know the system call functions and would not need me to declare them explicitly in the code.

Do I need to do something like this:

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

If so why does that make sense? I use other languages and never have to do this.

like image 821
AturSams Avatar asked Dec 04 '22 13:12

AturSams


1 Answers

Yes, you should include the correct header for every system function call you make. You don't write the declarations yourself—you'll get them wrong. Use the header!

For the functions you cite, the relevant headers are:

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

See POSIX 2008 to find the correct header for other POSIX functions.

The C99 standard requires that all functions are declared or defined before they are used.


For your own functions, you should emulate the 'system'. There will be a header that declares the function, the source file that implements it, and the other source files that use the function. The other source files use the header to get the declaration correct. The implementation file includes the header to make sure its implementation is consistent with what the other source files expect. So the header is the glue that holds it all together.

like image 77
Jonathan Leffler Avatar answered Dec 07 '22 03:12

Jonathan Leffler