I have seen strdup used in code samples on StackOverflow and have just tried to use it on Linux (3.0.0-21-generic x86_64).
The compiler (clang) knew it was in string.h, but still complained about not having a prototype even with string.h included. It turns out that strdup is wrapped in a #if defined, in string.h. I searched this site and found a post that said that strdup is a POSIX routine, not a C standard library routine.
The possible macros that will expose it are
- __USE_SVID
- __USE_BSD
- __USE_XOPEN_EXTENDED
- __USE_XOPEN2K8
Each one of those is undefined in features.h which is included by stdlib.h.
Why isn't a POSIX macro in that list and which macro/compiler switch are people using to expose strdup in string.h?
Edit: per Jim's comment below I found that
#define _POSIX_SOURCE 1
or
#define _POSIX_C_SOURCE 1
above
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
do not expose strdup on my system.
But these do:
#define _BSD_SOURCE 1
#define _SVID_SOURCE 1
Edit 2: Per Keith's comment, I found that this also works:
#define _POSIX_C_SOURCE 200809L
Edit 3: Per Jonathan's comment these also work
#define _XOPEN_SOURCE 500
#define _XOPEN_SOURCE 600
#define _XOPEN_SOURCE 700