使用c99的open_memstream函数

4

我正在尝试在我的C代码中使用open_memstream函数。然而,我似乎无法编译它。最小工作示例如下:

#include <stdio.h>

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

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

我还使用以下命令来编译它:

gcc -std=c99 -o test test.c

经过一些研究,我发现在包含stdio.h之前需要定义一个宏。然而,下面的示例代码没有用。

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

以下编译器警告被抛出;我认为第二个警告是由于第一个警告引起的。
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]

1
错误的宏定义。永远不要定义那些。阅读man open_memstream - n. m.
此外,我没有看到问题。无论你对那些警告感到困惑(顺便说一下,它们不是错误),我们无法读取你的思维。你需要告诉我们其中哪一部分让你感到困惑,以便我们可以帮助你纠正这种困惑。 - autistic
@Sebivor “which aren't errors” 请不要大声说出来,否则会给人留下你不知道它们是致命错误的印象。 - n. m.
@n.m. “它们是致命的”对于任何实现定义的内容都无效,因为它们可能在某些系统上不存在。你有什么确凿的来源来支持这个说法吗? - autistic
@Sebivor,“警告”在标准中并不存在。标准谈论的是诊断。我不是在谈论标准,而是在谈论这个特定实现中的特定警告。 - n. m.
显示剩余13条评论
1个回答

7
__USE_* 宏是 glibc 头文件内部使用的,自己定义它们是不起作用的。因此,你应该选择以下其中一种方法:
- 在编译命令中添加选项 -D,例如:-D_GNU_SOURCE - 在源代码中包含头文件 features.h
  • 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.)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接