【问题标题】:undefined reference to `crypt'对“crypt”的未定义引用
【发布时间】:2026-01-04 12:20:04
【问题描述】:

我正在使用我在网络某处找到的以下代码,当我尝试构建它时出现错误。编译没问题。

这是错误:

/tmp/ccCnp11F.o: In function `main':

crypt.c:(.text+0xf1): undefined reference to `crypt'

collect2: ld returned 1 exit status

这里是代码:

#include <stdio.h>
 #include <time.h>
 #include <unistd.h>
 #include <crypt.h>

 int main()
 {
   unsigned long seed[2];
   char salt[] = "$1$........";
   const char *const seedchars =
     "./0123456789ABCDEFGHIJKLMNOPQRST"
     "UVWXYZabcdefghijklmnopqrstuvwxyz";
   char *password;
   int i;

   /* Generate a (not very) random seed.
      You should do it better than this... */
   seed[0] = time(NULL);
   seed[1] = getpid() ^ (seed[0] >> 14 & 0x30000);

   /* Turn it into printable characters from `seedchars'. */
   for (i = 0; i < 8; i++)
     salt[3+i] = seedchars[(seed[i/5] >> (i%5)*6) & 0x3f];

   /* Read in the user's password and encrypt it. */
   password = crypt(getpass("Password:"), salt);

   /* Print the results. */
   puts(password);
   return 0;
 }

【问题讨论】:

标签: c cryptography linker-errors crypt


【解决方案1】:

crypt.c:(.text+0xf1): undefined reference to 'crypt' 是链接器错误。

尝试与-lcrypt 链接:gcc crypt.c -lcrypt

【讨论】:

  • 没有编译错误,只有链接错误。预处理器指令无关紧要。
【解决方案2】:

你必须在编译时添加-lcrypt...想象一下源文件名为crypttest.c,你会这样做:

cc -lcrypt -o crypttest crypttest.c

【讨论】:

    【解决方案3】:

    您可能忘记链接库

      gcc ..... -lcrypt
    

    【讨论】:

      【解决方案4】:

      这可能是由于两个原因:

      1. 与 crypt 库链接:使用-l&lt;nameOfCryptLib&gt; 作为gcc 的标志。
        示例:gcc ... -lcrypt 其中crypt.h 已编译到库中。
      2. 文件crypt.h 不在include path 中。只有当文件位于include path 中时,您才能在头文件周围使用&lt;&gt; 标记。要确保 crypt.h 存在于包含路径中,请使用 -I 标志,如下所示:gcc ... -I&lt;path to directory containing crypt.h&gt; ...
        示例:gcc -I./crypt 其中crypt.h 存在于当前目录的crypt/ sub-directory 中。

      如果您不想使用-I 标志,请将#include&lt;crypt.h&gt; 更改为#include "crypt.h"

      【讨论】: