Search code examples
cposixfreebsdposix-api

FreeBSD: Implicit declaration of getpagesize with _POSIX_C_SOURCE=200809L defined.


I am currently porting some OS related function of a software project from Linux to FreeBSD. Thereby, I recognized the following problem using getpagesize if _POSIX_C_SOURCE=200809Lis defined on FreeBSD 10.1.

I created a small test program

#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv)
{
        int i = getpagesize(); 

        return 0;
}

If I compile is using

cc test.c -o test 

it compiles without any warnings. But if I define _POSIX_C_SOURCE=200809L (result of the proper POSIX definition of getline function which I need in other parts of the code) I get:

cc test.c -D_POSIX_C_SOURCE=200809L
test.c:5:10: warning: implicit declaration of function 'getpagesize' is invalid in C99 [-Wimplicit-function-declaration]
        int i = getpagesize(); 
                ^

Although I included unistd.h as stated in the manpage of getpagesize. How can I make the code compiling without warnings with still defined _POSIX_C_SOURCE?


Solution

  • (1) The _POSIX_C_SOURCE is a wrong define. You need the _XOPEN_SOURCE. For example:

    cc -D_XOPEN_SOURCE=700 test.c 
    

    or

    cc -D_XOPEN_SOURCE=600 test.c 
    

    The 600 and 700 signify version of the Single Unix Specification (SUS for short, aka Open Group Specification, aka POSIX) your application expects from the system library. See here for the SUSv7.

    (2) BUT. That might still not work, because the getpagesize() is a BSD-specific function, which actually might be hidden if you try to compile the file in the POSIX-compliance mode.

    Normally you need nothing special to get access to the BSD functions on a BSD system, but portable way is to provide the _BSD_SOURCE define.

    The more portable, POSIX-compliant way to get the page size is sysconf(_SC_PAGE_SIZE) function. FreeBSD man page.

    P.S. Do not have a BSD at hand to test it.