clinuxsystem-callsglibcfallocate

error: FALLOC_FL_KEEP_SIZE undeclared (first use in this function)


As per the man page, I have defined _GNU_SOURCE before the inclusion of <fcntl.h>:

#include <stdio.h>

#define _GNU_SOURCE    /* For Linux's fallocate(). */
#define HAVE_FALLOCATE 1

#include <fcntl.h>

int main(void)
{
    printf("%d\n", FALLOC_FL_KEEP_SIZE);
}

which I compiled with:

gcc-13 -std=gnu2x c.c

But this fails with:

error: `FALLOC_FL_KEEP_SIZE` undeclared (first use in this function)

Some stats about the environment:

OS: Linux Mint 21.2 x86_64
Kernel: 5.15.0-112-generic
GLIBC Version: GNU C Library (Ubuntu GLIBC 2.35-0ubuntu3.8) stable release 2.35
Compiler: gcc version 13.1.0 (Ubuntu 13.1.0-8ubuntu1~22.04)

Running grep -r FALLOC_FL_KEEP_SIZE /usr/include returned:

/usr/include/linux/falloc.h:#define FALLOC_FL_KEEP_SIZE 0x01 /* default is extend size */
/usr/include/linux/falloc.h: * with fallocate. Flag FALLOC_FL_KEEP_SIZE should cause the inode

Solution

  • The problem is that you did #include <stdio.h> before #define _GNU_SOURCE. As-is, I get the same error as you, but with that fixed, it compiles fine. Per man 7 feature_test_macros:

           NOTE: In order to be effective, a feature test macro must be
           defined before including any header files.  This can be done
           either in the compilation command (cc -DMACRO=value) or by
           defining the macro within the source code before including any
           headers.  The requirement that the macro must be defined before
           including any header file exists because header files may freely
           include one another.  Thus, for example, in the following lines,
           defining the _GNU_SOURCE macro may have no effect because the
           header <abc.h> itself includes <xyz.h> (POSIX explicitly allows
           this):
    
               #include <abc.h>
               #define _GNU_SOURCE
               #include <xyz.h>