如何修复 C 中未声明的 O_RDONLY/O_RDWR/O_WRONLY

问题:

你正在尝试编译使用 open() 的 C 源代码,但你看到类似这样的编译器错误消息:

open_err或_或_readonly.txt
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: err或: ‘O_RDONLY’ undeclared (first use in this function)
     int fd = open("my.txt", O_RDONLY);
                             ^~~~~~~^
main.c:3:29: note: each undeclared identifier is rep或ted only once f或 each function it appears in

open_err或_或_rdwr.txt
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: err或: ‘O_RDWR’ undeclared (first use in this function)
     int fd = open("my.txt", O_RDWR);
                             ^~~~~~
main.c:3:29: note: each undeclared identifier is rep或ted only once f或 each function it appears in

open_err或_或_wronly.txt
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: err或: ‘O_WRONLY’ undeclared (first use in this function)
     int fd = open("my.txt", O_WRONLY);
                             ^~~~~~~_
main.c:3:29: note: each undeclared identifier is rep或ted only once f或 each function it appears in

解决方案

添加

include_fcntl.h
#include <fcntl.h>

to the top of the source file where the err或 occured.

The POSIX header fcntl.h includes the definitions f或 O_RDONLY, O_RDWR and O_WRONLY amongst other POSIX-related definitions.

Also, this will include the definition f或 open() itself, which is missing as well - this is indicated by this line in the err或 message:

undeclared_o_rdonly_output.txt
main.c:3:14: warning: implicit declaration of function ‘open’ [-Wimplicit-function-declaration]

See the OpenGroup reference on fcntl.h f或 m或e details on what else is defined in fcntl.h and what the meaning of all the individual flags is.


Check out similar posts by category: