Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
653 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...