How to fix undeclared O_RDONLY/O_RDWR/O_WRONLY in C
Problem:
You are trying to compile C sourcecode that uses open(), but you see a compiler error message like this:
main.c: In function ‘main’:
main.c:3:14: warning: implicit declaration of function ‘open’ [-Wimplicit-function-declaration]
int fd = open("my.txt", O_RDONLY);
^~~~
main.c:3:29: error: ‘O_RDONLY’ undeclared (first use in this function)
int fd = open("my.txt", O_RDONLY);
^~~~~~~~
main.c:3:29: note: each undeclared identifier is reported only once for each function it appears in
or
main.c: In function ‘main’:
main.c:3:14: warning: implicit declaration of function ‘open’ [-Wimplicit-function-declaration]
int fd = open("my.txt", O_RDWR);
^~~~
main.c:3:29: error: ‘O_RDWR’ undeclared (first use in this function)
int fd = open("my.txt", O_RDWR);
^~~~~~
main.c:3:29: note: each undeclared identifier is reported only once for each function it appears in
or
main.c: In function ‘main’:
main.c:3:14: warning: implicit declaration of function ‘open’ [-Wimplicit-function-declaration]
int fd = open("my.txt", O_WRONLY);
^~~~
main.c:3:29: error: ‘O_WRONLY’ undeclared (first use in this function)
int fd = open("my.txt", O_WRONLY);
^~~~~~~~
main.c:3:29: note: each undeclared identifier is reported only once for each function it appears in
Solution
Add
#include <fcntl.h>
to the top of the source file where the error occured.
The POSIX header fcntl.h
includes the definitions for O_RDONLY
, O_RDWR
and O_WRONLY
amongst other POSIX-related definitions.
Also, this will include the definition for open()
itself, which is missing as well - this is indicated by this line in the error message:
main.c:3:14: warning: implicit declaration of function ‘open’ [-Wimplicit-function-declaration]
See the OpenGroup reference on fcntl.h
for more details on what else is defined in fcntl.h
and what the meaning of all the individual flags is.