1

我正在使用这个:

#if !defined(_SVID_SOURCE) || !defined(_BSD_SOURCE) || _XOPEN_SOURCE < 500 || !(_XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED) \
|| _POSIX_C_SOURCE < 200809L
char * strdup(const char *s)
{
  char *buffer = malloc(strlen(s) + 1);

  if(buffer != NULL)
    strcpy(buffer, s);

  return buffer;
}
#endif

但是是否有可能出现重新声明错误?也许进入一些 gcc 版本或类似 gcc 的编译器?例如,我想让它与没有strdup(),的版本(标准)兼容-ansi

另外,我怎样才能使它更便携?

4

3 回答 3

2

这绝对是功能测试宏的错误使用。实现没有定义功能测试宏来告诉应用程序什么是可用的;它们由应用程序定义,以要求实现提供对特定标准(特定版本)的一致性。

您应该用来测试实现支持的宏在unistd.h

  • _POSIX_VERSION- 支持的 POSIX 版本。200809L是最新的。
  • _XOPEN_VERSION- X/Open Portability Guide 的版本,现在称为 POSIX 的“XSI”选项。最新的是700(来自SUSv4)。600(SUSv3) 很常见。500(SUSv2)严重过时。
  • _POSIX_THREADS- pthreads 的版本(应该与 相同_POSIX_VERSION;自 POSIX 2008 起强制)
  • ...
于 2012-09-28T18:12:29.543 回答
1

Looking in the string.h on my platform (linux, gnu libc 2.16) I found :

#if defined __USE_SVID || defined __USE_BSD || defined __USE_XOPEN_EXTENDED \
    || defined __USE_XOPEN2K8
/* Duplicate S, returning an identical malloc'd string.  */
extern char *strdup (const char *__s)
     __THROW __attribute_malloc__ __nonnull ((1));
#endif

The #ifs are slightly different, I don't know the influence between those I found in my header and the ones your are using.
About the second question, you could use the autotools to create a config.h header describing the capabilities of the compiling platform, and use your own versions of missing functions.
In addition you could also use the gnulib "source library" which provides implementation of defective or missing functions (like strdup)
Using autotools should prevent any redeclaration error.

于 2012-09-28T16:32:51.313 回答
1

是的,如果它已经定义,您将在 strdup 上重新声明。我知道解决此类问题的唯一方法是将 strdup 宏定义为其他内容(例如 _strdup),然后使用其他名称定义 strdup。这有点难看,但它完成了工作。

对于您的第一个问题,不,您无法确定预处理器是否存在函数。看到这个帖子

于 2012-09-28T16:09:26.700 回答