简体   繁体   中英

Use open_memstream with 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]

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM