If using C++, consider using C++ headers. string.h
is a C header, <cstring>
is its C++ equivalent.
#include <cstdlib>
#include <cstring>
#include <cstdio>
int main()
{
const char * first = "asdf qwerty";
printf("%s\n", first);
char * second = strdup(first);
second[4] = '\0';
printf("%s\n", second);
free(second);
return 0;
}
The above code compiles fine with GCC 9.4.0 g++ -Wall -Wextra -std=c++11
.
Bonus meme: if you do want strdup()
in C (before C23), use a GCC Feature Test Macro such as __STDC_WANT_LIB_EXT2__
or _POSIX_C_SOURCE
. The former enables C-standard extensions, the latter enables POSIX extensions. It is important this macro be defined before any of your includes, as shown below.
To quote from strdup - cppreference.com:
... strdup is only guaranteed to be available if __STDC_ALLOC_LIB__
is defined by the implementation and if the user defines __STDC_WANT_LIB_EXT2__
to the integer constant 1
before including string.h.
#define __STDC_WANT_LIB_EXT2__ 1
/* ...or...
* #define _POSIX_C_SOURCE 200809L
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main(void)
{
const char * first = "asdf qwerty";
printf("%s\n", first);
char * second = strdup(first);
second[4] = '\0';
printf("%s\n", second);
free(second);
return 0;
}
#include
<cstring>` and usingstd::strdup
, that's the "C++ way". (Still isn't an answer, though, since that should be valid too, IIRC.) – Competency_CRTIMP char* __cdecl __MINGW_NOTHROW strdup (const char*) __MINGW_ATTRIB_MALLOC;
in my headers. It works with that. – Milagrosmilam