警告:函数“vasprintf”的隐式声明?

Dan*_*jel 1 c linux

#define _GNU_SOURCE\n\n#include <errno.h>\n#include <getopt.h>\n#include <stdarg.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include <inttypes.h>\n\nstatic int mylog(const char *format, ...)\n{\n    va_list args;\n    char *str = NULL;\n\n    va_start(args, format);\n    vasprintf(&str, format, args);\n    va_end(args);\n\n    fprintf(stdout, "Test >> %s", str);\n\n    free(str);\n    return 0;\n}\n\nint main(int argc, char *argv[])\n{\n    //...\n}\n
Run Code Online (Sandbox Code Playgroud)\n

warning: implicit declaration of function \xe2\x80\x98vasprintf\xe2\x80\x99; did you mean \xe2\x80\x98vsprintf\xe2\x80\x99? [-Wimplicit-function-declaration]

\n

为什么编译器会发出警告vasprintf?

\n

gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)

\n

Fra*_*e_C 5

要启用动态分配功能(ISO/IEC TR 24731-2:2010 中的功能),您必须在包含标头之前__STDC_WANT_LIB_EXT2__定义宏:1stdio.h

#define __STDC_WANT_LIB_EXT2__ 1  //Define you want TR 24731-2:2010 extensions
#define _GNU_SOURCE

#include <errno.h>
#include <getopt.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <inttypes.h>

static int mylog(const char *format, ...)
{
    va_list args;
    char *str = NULL;

    va_start(args, format);
    vasprintf(&str, format, args);
    va_end(args);

    fprintf(stdout, "Test >> %s", str);

    free(str);
    return 0;
}

int main(int argc, char *argv[])
{
    //...
}
Run Code Online (Sandbox Code Playgroud)

请注意,这些扩展是可选的,GCC 并未实现所有扩展,其他编译器可以实现不同的集。