Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use open_memstream with c99

Tags:

c

posix

c99

I am trying to use the open_memstream function in my C code. However I cannot seem to compile it. Minimal working example as follows:

#include <stdio.h>

int main(void) {
    char *buf;
    size_t sz;

    FILE *stream = open_memstream(&buf, &sz);
    putc('A', stream);
    fclose(stream);
}

And I also use the following command to compile it:

gcc -std=c99 -o test test.c

After some research, I found that I need to define a macro before I include stdio.h. However the following example code was to no avail.

#define __USE_POSIX
#define __USE_XOPEN
#include <stdio.h>

The following compiler warnings are thrown; I assume the second warning is because of the first one.

test.c:7:17: warning: implicit declaration of function ‘open_memstream’ [-Wimplicit-function-declaration]
FILE *stream = open_memstream(&buf, &sz);
             ^
test.c:7:17: warning: initialization makes pointer from integer without a cast [-Wint-conversion]
like image 902
Bert Avatar asked Mar 08 '23 11:03

Bert


1 Answers

The __USE_* macros are internal to glibc's headers, and defining them yourself does not work. You should instead do one of the following:

  • Compile your program with -std=gnu11 instead of -std=c99 and don't define any special macros. This is the easiest change. Conveniently, -std=gnu11 is the default with newer versions of GCC.

  • If you have some concrete reason to want to select an old, strict conformance mode, but also you want POSIX extensions to C, then you can use the documented POSIX feature selection macros:

    #define _XOPEN_SOURCE 700
    

    or

    #define _POSIX_C_SOURCE 200809L
    

    These must be defined before including any standard headers. The difference is that _XOPEN_SOURCE requests an additional set of features (the "XSI" functions). See the Feature Test macros section of the glibc manual for more detail.

    Note that if you need to request strict conformance mode from the library, using a -std=cXX option, then you almost certainly also want to use the -Wall and -Wpedantic options to enable strict conformance checking for the language. (You should use at least -Wall even if you don't need strict conformance checking.)

like image 90
zwol Avatar answered Mar 21 '23 00:03

zwol