简体   繁体   English

将open_memstream与c99一起使用

[英]Use open_memstream with c99

I am trying to use the open_memstream function in my C code. 我试图在我的C代码中使用open_memstream函数。 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 . 经过一些研究,我发现在包含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. __USE_*宏是glibc头文件的内部,自己定义它们不起作用。 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. 使用-std=gnu11而不是-std=c99编译程序,并且不要定义任何特殊的宏。 This is the easiest change. 这是最简单的改变。 Conveniently, -std=gnu11 is the default with newer versions of GCC. 方便地, -std=gnu11是较新版本的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: 如果您有一些具体的理由想要选择旧的,严格的一致性模式,但是您希望POSIX扩展到C,那么您可以使用记录的 POSIX功能选择宏:

     #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). 不同之处在于_XOPEN_SOURCE请求一组额外的功能(“XSI”功能)。 See the Feature Test macros section of the glibc manual for more detail. 有关更多详细信息,请参阅glibc手册的“ 功能测试宏”部分。

    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 . 请注意,如果您需要从库中请求严格的一致性模式,使用-std=cXX选项,那么您几乎肯定也想使用-Wall-Wpedantic选项来启用对该语言的严格一致性检查。 (You should use at least -Wall even if you don't need strict conformance checking.) (你至少应该使用-Wall即使你并不需要严格的一致性检查。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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