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:
a) What happens when I write my own function with the same name as a built-in function?
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?
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