【问题标题】:Is the crypt() function declared in unistd.h or crypt.h?crypt() 函数是在 unistd.h 还是 crypt.h 中声明的?
【发布时间】:2011-05-25 16:43:59
【问题描述】:

我正在使用 GCC 4.6.0(在其他无法识别的平台上)。

我正在使用crypt() 函数来加密密码。

我之前从未使用过该功能,所以我查看了主页:

man 3 crypt

它说要包含unistd.h 标头。

但是,当我这样做时,我收到了 crypt 函数的隐含警告。

warning: implicit declaration of function ‘crypt’ [-Wimplicit-function-declaration]

我进行了一些搜索,发现您必须包含crypt.h。但是,手册页中怎么没有说呢?

【问题讨论】:

  • 请发布您在编译时收到的确切警告。
  • @Michael,我已将我的问题附加到我收到的警告中。
  • 你用 -lcrypt 编译?
  • C : crypt function的可能重复
  • @Henno,是的,我正在使用 lcrypt libcrypt.so.1 => /lib64/libcrypt.so.1 进行编译。来自 ldd 可执行文件。

标签: c crypt


【解决方案1】:

它还在我的手册页中显示#define _XOPEN_SOURCE(在包括unistd.h 之前)。所以你应该添加它来暴露crypt的声明。

编辑

我刚试过。包括unistd.h #define _XOPEN_SOURCE 在它起作用之前。仅包括它是不够的。

使用

gcc version 4.6.0 20110429
GNU C Library stable release version 2.13

调查unistd.h

/* XPG4.2 specifies that prototypes for the encryption functions must
   be defined here.  */
#ifdef  __USE_XOPEN
/* Encrypt at most 8 characters from KEY using salt to perturb DES.  */
extern char *crypt (__const char *__key, __const char *__salt)
     __THROW __nonnull ((1, 2));

【讨论】:

  • 我确实添加了 _XOPEN_SOURCE。但是,我仍然收到警告。
  • 您不仅要定义它,还要给它一个值。对于最新标准,该值应为 700。
  • @R.. 这听起来很明智,但手册页上写着#define _XOPEN_SOURCE。不过我没试过。
  • 手册页是个笑话。阅读the standard
  • @ant2009:#define _XOPEN_SOURCE 700 行必须在所有包含文件之前——如果你把它放在其他包含文件之后,即使它在 <unistd.h> 之前,它也行不通.
【解决方案2】:

crypt() 的 POSIX 标准规定它应该在 <unistd.h> 中声明,所以这就是您需要包含的内容。

但是,根据您指定的其他编译器选项,您可能会看到也可能不会看到。

我目前使用一个名为 "posixver.h" 的标题,其中包含代码:

#ifndef JLSS_ID_POSIXVER_H
#define JLSS_ID_POSIXVER_H

/*
** Include this file before including system headers.  By default, with
** C99 support from the compiler, it requests POSIX 2001 support.  With
** C89 support only, it requests POSIX 1997 support.  Override the
** default behaviour by setting either _XOPEN_SOURCE or _POSIX_C_SOURCE.
*/

/* _XOPEN_SOURCE 700 is loosely equivalent to _POSIX_C_SOURCE 200809L */
/* _XOPEN_SOURCE 600 is loosely equivalent to _POSIX_C_SOURCE 200112L */
/* _XOPEN_SOURCE 500 is loosely equivalent to _POSIX_C_SOURCE 199506L */

#if !defined(_XOPEN_SOURCE) && !defined(_POSIX_C_SOURCE)
#if __STDC_VERSION__ >= 199901L
#define _XOPEN_SOURCE 600   /* SUS v3, POSIX 1003.1 2004 (POSIX 2001 + Corrigenda) */
#else
#define _XOPEN_SOURCE 500   /* SUS v2, POSIX 1003.1 1997 */
#endif /* __STDC_VERSION__ */
#endif /* !_XOPEN_SOURCE && !_POSIX_C_SOURCE */

#endif /* JLSS_ID_POSIXVER_H */

在我工作的系统上,将_XOPEN_SOURCE 设置为 700 将是一种挫败感和徒劳的练习,无论我多么希望能够这样做。但是这些选项通常可以让我的代码在 Linux、HP-UX、MacOS X、AIX 和 Solaris 上正常工作——我通常在这些类似 Unix 的平台上工作。

当我将 GCC 设置为 -std=c99 模式时,这有效。如果你使用-std=gnu99,你可能根本不需要标题;它会自动启用 C99 标准加扩展。

顺便说一句,我曾经将这节放在各个源文件的顶部。随着包含该节的文件数量增加(侵占数百个文件),我意识到当我需要调整设置时,我面临着一项巨大的编辑工作。现在我有了一个标题,并且我正在将它改装到具有该节的文件中,因此我更改了一个文件(标题)以对我的所有代码进行更改 - 一旦我完成了我所做的破坏。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    • 2010-11-27
    • 1970-01-01
    • 2019-03-09
    相关资源
    最近更新 更多