cc99

How to use ftruncate in c99 without warning


I want to use ftruncate function in my code. I have to compile with option std=c99. I get warning:

In function ‘test’:
warning: implicit declaration of function ‘ftruncate’ [-Wimplicit-function-declaration]

I tied to find on the Internet any solution which can solve this problem but I don't succeeded in.

I use ftrucnate because I want to clear content of an opened file after I get lock (flock).


Solution

  • Since ftruncate() isn't a standard C function, and you've asked for standards enforcement, you need to define the appropriate feature test macros (see feature_test_macros(7)).

    From the ftruncate(2) manpage:

       ftruncate():
           _BSD_SOURCE || _XOPEN_SOURCE >= 500 ||
           _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED
           || /* Since glibc 2.3.5: */ _POSIX_C_SOURCE >= 200112L
    

    In other words, to expose the ftruncate() function you must define one of these macros, for example:

    gcc -c -std=c99 -D_XOPEN_SOURCE=500 myfile.c