C strndup隐式声明

Cow*_*s42 4 c

我正在尝试使用strndup函数,但是我得到了错误

错误:函数'strndup'的隐式声明[-Werror = implicit-function-declaration]

我四处搜索,发现它不是标准函数,因此我必须使用不同的标志进行编译.但是,我通过以下编译收到同样的问题:

-std=gnu11
-Wall
-Wextra
-Werror
-Wmissing-declarations
-Wmissing-prototypes
-Werror-implicit-function-declaration
-Wreturn-type
-Wparentheses
-Wunused
-Wold-style-definition
-Wundef
-Wshadow
-Wstrict-prototypes
-Wswitch-default
-Wunreachable-code
-D_GNU_SOURCE
Run Code Online (Sandbox Code Playgroud)

我正在做一个任务,因此我必须使用所有这些,但我发现我必须使用'-D_GNU_SOURCE'进行编译才能使错误消失,但事实并非如此.

编辑:

我也包括这些:

#define __STDC_WANT_LIB_EXT2__ 1
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
Run Code Online (Sandbox Code Playgroud)

非常感谢帮助解决这个问题.

chq*_*lie 7

strdupstrndup不是他们在Posix.1-2008标准化,并宣布在标准C的一部分<string.h>在POSIX系统.你有<string.h>吗?

如果您的系统不提供这些功能,您可以通过以下方式自行定义:

#include <string.h>

char *strdup(const char *s) {
    size_t size = strlen(s) + 1;
    char *p = malloc(size);
    if (p != NULL) {
        memcpy(p, s, size);
    }
    return p;
}

char *strndup(const char *s, size_t n) {
    char *p = memchr(s, '\0', n);
    if (p != NULL)
        n = p - s;
    p = malloc(n + 1);
    if (p != NULL) {
        memcpy(p, s, n);
        p[n] = '\0';
    }
    return p;
}
Run Code Online (Sandbox Code Playgroud)