Martin
Martin

Reputation: 9359

Headers for C POSIX functions

Where or how can I find the correct C headers to include in a C++ program to obtain the declaration of C functions declared in a POSIX compliant environment?

I'm asking this because I needed to use the open() system call in my C++ program for my purposes, so I initially tried to include the headers mentioned in the online documentation about open() (in the SYNOPSIS section), which are sys/stat.h and fcntl.h. However when trying to compile, the compiler complained that open() was not declared. After a search on google, I found that another possibility was unistd.h. I tried using that header and the program compiled. So I went back to the POSIX documentation to read more about unistd.h to check if open() was mentioned there, but I could not find anything about it.

What am I doing wrong? Why is there this discrepancy between the POSIX documentation and my GCC environment?

Upvotes: 5

Views: 3400

Answers (1)

On my Linux Debian/Sid, the man 2 open page states:

SYNOPSIS
   #include <sys/types.h>
   #include <sys/stat.h>
   #include <fcntl.h>

So you need to include all three above files. And open is declared in /usr/include/fcntl.h but needs declaration from the other two includes.

And the following test file

/* file testopen.c */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int
testopen (void)
{
  return open ("/dev/null", O_RDONLY);
}

compiles with gcc -Wall -c testopen.c without any warnings.

Upvotes: 9

Related Questions