Behebung von undeclared O_RDONLY/O_RDWR/O_WRONLY in C

English Deutsch

Problem:

Du versuchst, C-Quellcode zu kompilieren, der open() verwendet, aber du siehst eine Compiler-Fehlermeldung wie diese:

open_error_or_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: 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

open_error_or_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: 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

open_error_or_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: 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

Lösung

Füge hinzu

include_fcntl.h
#include <fcntl.h>

am Anfang der Quelldatei hinzu, wo der Fehler aufgetreten ist.

Der POSIX-Header fcntl.h enthält die Definitionen für O_RDONLY, O_RDWR und O_WRONLY unter anderen POSIX-bezogenen Definitionen.

Außerdem wird dies die Definition für open() selbst einschließen, welche ebenfalls fehlt - dies wird durch diese Zeile in der Fehlermeldung angezeigt:

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

Siehe die OpenGroup-Referenz zu fcntl.h für weitere Details, was sonst noch in fcntl.h definiert ist und was die Bedeutung aller einzelnen Flags ist.


Check out similar posts by category: C/C++, GCC Errors