Search code examples
cstrdup

Which macro is being used with strdup on Linux?


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

Solution

  • The __USE... macros are for internal use. You should define _POSIX_SOURCE, or possibly one of the other feature macros as described in the comments in your feature.h ... for example, from a version I just grabbed off the web (apparently an old and somewhat obsolete version),

       __STRICT_ANSI__  ANSI Standard C.
       _POSIX_SOURCE    IEEE Std 1003.1.
       _POSIX_C_SOURCE  If ==1, like _POSIX_SOURCE; if ==2 add IEEE Std 1003.2.
       _BSD_SOURCE      ANSI, POSIX, and 4.3BSD things.
       _SVID_SOURCE     ANSI, POSIX, and SVID things.
       _GNU_SOURCE      All of the above, plus GNU extensions.
    

    So defining _GNU_SOURCE would get you everything.

    Edit: from the comment by Keith Thompson, you need

     #define _POSIX_C_SOURCE 200809L
    

    for strdup.