ANONYMOUS wrote:
> In the recent lab I was attempting to use strdup() and compiling with the normal compilation command and the compiler was not recognising strdup() as a valid standard C function. I believe we are required to use it in this next project, how are we meant to run our code using that? I believe it works on Macs but WSL on Windows for me doesn't.
The function
strdup()
has never been defined in a C standard, until its appearance in the new C23 standard (though why release it on 1st April!?)
https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3096.pdf
But
strdup()
has long been defined in earlier POSIX, XOPEN, and GNU standards, and if we state which standards we want our programs to conform to, then we can access the
strdup()
declaration from the <string.h> header file.
The 'correct' way to do this is to define the required standard before #include-ing the header file. For example, if we wish to follow the POSIX standard released September 2008, we could use:
#define _POSIX_C_SOURCE 200809L
#include <string.h>
A less correct (less pedantic) way to declare
strdup()
is to just provide the declaration given in man entry for
strdup()
:
extern char *strdup(const char *str);
All of the above applies if using Linux; Apple 'holds your hand' by silently supporting the 2001 POSIX standard (and beyond), so
strdup()
is always available.