的strdup()函数 [英] strdup() function

查看:180
本文介绍了的strdup()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我开始意识到,在的strdup()功能我很喜欢用这么多的OS X是不是ANSI C的一部分,但POSIX的一部分。我不想重写所有我的code,所以我觉得我只是会写我自己的的strdup()功能。这并不难,真的,这只是一个的malloc()的strcpy()。无论如何,我有作用,但如果我写这个函数,并将其链接到我的code我在做什么,它已经在libc的存在?请问我的链接器或编译器允许我基本上定义我自己的版本功能,还是我给它一个名字吗?这将是非常方便的,如果有重复使用相同的名称的方式,所以如果的strcpy()在用户的libc的存在,他们可以使用该,但如果它没'吨他们存在的libc他们可以使用我的版本代替,用尽可能少code修改成为可能。

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.

短的版本:

一)当我写我自己的函数具有相同的名称作为一个内置功能,会发生什么?

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

二)我能做些什么,以避免不好的事情发生在我身上就没有这样的平台的strdup()无需重写我的所有code不使用的strdup(),它只是有点乏味?

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?

推荐答案

通常情况下,你只需使用#如果定义要在一定的编译时的功能。如果内置库没有定义的strdup,有自己定义它没有问题(除如果他们在将来定义它,你必须把它拿出来。)

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

这篇关于的strdup()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆