Chris Lutz
Chris Lutz

Reputation: 697

When writing my own "strdup" function, how do I avoid conflicts with platforms that already provide one?

I recently became aware that the strdup() function I've enjoyed using so much on OS X is not part of ANSI C, but part of POSIX. I don't want to rewrite all my code, so I think I'm just going to write my own strdup() function. It's not that hard, really, it's just a malloc() and a strcpy().

Anyway, I have the function, but what am I doing if I write this function and link it to my code, and it already exists in the libc? Will my linker or compiler allow me to basically define my own version of the function, or do I have to give it another name? It would be terribly convenient if there was a way to reuse the same name, so that if strcpy() exists in the user's libc they could use that, but if it didn't exist in their libc they could use my version instead, with as little code change as possible.

The short version:

Upvotes: 17

Views: 25499

Answers (8)

vjalle
vjalle

Reputation: 953

I'm afraid, it's difficult to solve automatically and in a portable way. I believe the best option is a precompile option whether the library function should be used or your own implementation. If you decide to define your own function with the same name and signature, it will work down to linking (won't interfere with included headers), where you'll get a duplicate symbol error.

Most linkers have special options to only fetch missing symbols from libraries and ignore duplicate ones. This can be a solution, but might not be available in all linkers, might have unwanted effects and it's additional porting effort.

Another idea is defining your function as attribute((weak)). The linker will then use your function when it's not available in the libraries, and use the library one when it's there, without issuing any warning/error. However, weak symbols are not always supported, either.

If you're building for desktop/mobile and you're sure that modern compilers are available, go for weak. If there is a risk that some weird compiler for some weird microcontroller does not support weak symbols, use a precompile option and #ifdef.

And you should also consider the answer from Pat, that's downvoted to oblivion. You're not forced to always use stdlib calls just because it's possible. It's OK to implement trivial functionality in your code, especially when it's a not very well supported function. Not all stdlib calls are useful, safe or good quality.

Upvotes: 0

Evan Teran
Evan Teran

Reputation: 90493

You could just use a macro; this way you can use the old name, but linker will see a different name:

char *my_strdup(const char *s)
{
    size_t len = strlen(s) + 1;
    char *p = malloc(len);
    if (p) { memcpy(p, s, len); }
    return p;
}
/* this goes in whatever header defines my_strdup */
char *my_strdup(const char *s);
#define strdup(x) my_strdup(x)

Upvotes: 7

quinmars
quinmars

Reputation: 11573

As Rob Kennedy noted the best way is to test inside your building scripts if this functions exists or not. I know that it is fairly easy with autoconfig, but probably with other cross-platform building scripts tools, too.

Then you simply place in your header file:


#ifndef HAVE_STRDUP
# ifdef HAVE__STRDUP
#  define strdup _strdup
# else
#  define strdup my_strdup
# endif
#endif

If strdup already exists on the target platform the libc version is used, if not your custom my_strdup function will be used.

EDIT: I should have added an explination why it is better.

First the compiler is unrelated to the existence of a function in the libc. For example take the function strlcpy. It is present on FreeBSD but not on Linux (glibc), although both are using gcc by default. Or what happens if someone is going to compile your code with clang?

Second a platform check (I don't know if there is a standard way) will only work if you explicitly add for every plattform you want to support the correct preprocessor conditional. So assuming you have mastered to compile your application on OSX and Win32 and you want to compile it now on Linux, you'll have to go through all preprocessor conditionals to see if they work for Linux. Maybe you also want to support FreeBSD, OpenBSD, etc.? Same work again. With a test in your building scripts, it may compile without any additional work.

Upvotes: 7

Pat
Pat

Reputation: 21

If anyone else reads this: Don't use a platform's strdup() even if available, and don't waste time/effort with autoconf/automake just to use it. Seriously, how hard is this:

char* mystrdup(const char* str)
{
 return strcpy(malloc( strlen(str) + 1),str);
}

Does this really warrant #ifdefs? Compiler checks? K.I.S.S.

Upvotes: -3

Chris Young
Chris Young

Reputation: 15767

You should also consider avoiding the creation of any identifier (including a function) that begins with str[a-z]. While this isn't reserved, the C standard (ISO/IEC 9899:1999) section 7.26.11 (future library directions) states "Function names that begin with str, mem, or wcs and a lowercase letter may be added to the declarations in the header."

Upvotes: 3

Eddie
Eddie

Reputation: 54421

FYI: I've never personally seen an environment that did not define strdup().

Upvotes: 1

LeopardSkinPillBoxHat
LeopardSkinPillBoxHat

Reputation: 29431

a) What happens when I write my own function with the same name as a built-in function?

You cannot re-define a function that already exists in a header file you are including. This will result in a compilation error.

b) What can I do to avoid bad things happening to me on platforms that don't have strdup() without rewriting all my code to not use strdup(), which is just a bit tedious?

I would recommend creating your own wrapper function to strdup, and replacing all your calls to use the new wrapper function. For example:

char *StringDuplicate(const char *s1)
{
#ifdef POSIX
    return strdup(s1);
#else
    /* Insert your own code here */
#endif
}

Changing all your calls from strdup to StringDuplicate() should be a simple find-and-replace operation, making it a feasible approach. The platform-specific logic will then be kept in a single location rather than being scattered throughout your codebase.

Upvotes: 4

Eclipse
Eclipse

Reputation: 45533

Usually, you just use an #if to define the function you want when under a certain compiler. If the built-in library doesn't define strdup, there is no problem in defining it yourself (other than if they do define it in the future, you'll have to take it out.)

// Only define strdup for platforms that are missing it..
#if COMPILER_XYZ || COMPILER_ABC
char *strdup(const char *)
{
   // ....
}
#endif

Upvotes: 20

Related Questions