cgccwarnings

How do I resolve this warning about implicit declaration of mempcpy() after switch to Win11 WSL


Today I switched to Win11 and can no longer compile a program i was working on with gcc in wsl without "implicit declaration of function ‘mempcpy’" warnings. Before switching to Win 11 (from Win10) everything worked fine.

I get the same behavior for the following test program as well:

#include <stdio.h>
#include <string.h>

int main() {
    char src[] = "Hello, World!";
    char dest[20];

    char* p = mempcpy(dest, src, strlen(src) + 1);
    printf("%s\n", dest);

    //Do something with pointer p

    return 0;
}

Compiling with "gcc -std=gnu17 -o test main.c" gives the the respective warning.

Compiling with clang gives a similar warning and the note: "include the header <string.h> or explicitly provide a declaration for 'mempcpy'"

I tried/checked the following things:

1.) Header in include library: The string.h header is in the include path and has the definition for mempcpy. I even reinstalled libc6-dev to ensure the header file is fine. If I remove the include for stdio.h I get an additional error so it seems that this header is found successfully. stdio.h and string.h are in the same folder so I assume the compiler should be able to see string.h as well.

2.) Using the correct -std=...: This was not necessary before and does not seem to change anything with the new OS installation. I tried several options but nothing changed the behavior. In string.h there is the line #ifdef __USE_GNU. But I assume this would be set to true if std=gnu17 or something similar is set.

3.) Explicitely adding the declaration above int main(){..} with adding the line void *mempcpy(void *dest, const void *src, size_t n);: This removed the warning but it only masks the issue.

If i ignore the warning my program as well as the test program runs fine, but I use -Werror for compilation of the program I am working on so I can not ignore it in this case (even if I wanted to).

OS: Ubuntu 22.04 (in WSL Win11 (10.0.26100)), Compiler: gcc ((Ubuntu 11.4.0-1ubuntu1~22.04.2) 11.4.0)

I am really unsure what else to check/try.


Solution

  • mempcpy isn't a standard C library function, but a GNU extension. As seen in its man page, the following is required to declare it:

    #define _GNU_SOURCE
    #include <string.h>
    

    So the fix is to add #define _GNU_SOURCE before any includes.

    That said, since you discard the value returned by mempcpy, and since mempcpy only varies from the standard C library function memcpy in the value it returns, you could swap in memcpy for mempcpy. Or better yet, you could use strcpy(dest, src).