15

有人告诉我使用该strlcpy功能而不是strcpy这样

#include <stdio.h>
#include <string.h>

void main()
{
   char var1[6] = "stuff";
   char var2[7] = "world!";
   strlcpy(var1, var2, sizeof(var2));
   printf("hello %s", var1);

} 

当我编译文件时,它给了我以下错误:

C:\Users\PC-1\AppData\Local\Temp\ccafgEAb.o:c.c:(.text+0x45): undefined referenc
e to `strlcpy'
collect2.exe: error: ld returned 1 exit status

注意:我已经安装了 MinGW(Minimalist GNU for Windows)并且gcc版本是4.7.2

问题是什么?

4

4 回答 4

7

对“strlcpy”的未定义引用

当链接器(collect2如果您使用 gcc)找不到它抱怨的函数的定义(不是声明或原型,而是定义函数代码的定义)时,就会发生这种情况。

在您的情况下,它可能会发生,因为没有共享对象或库与strlcpy' 代码链接。如果您确定有一个包含代码的库并且想要链接它,请考虑使用-L<path_to_library>传递给编译器的参数指定库的路径。

于 2013-08-31T10:53:26.430 回答
7

将此代码添加到您的代码中:

#ifndef HAVE_STRLCAT
/*
 * '_cups_strlcat()' - Safely concatenate two strings.
 */

size_t                  /* O - Length of string */
strlcat(char       *dst,        /* O - Destination string */
              const char *src,      /* I - Source string */
          size_t     size)      /* I - Size of destination string buffer */
{
  size_t    srclen;         /* Length of source string */
  size_t    dstlen;         /* Length of destination string */


 /*
  * Figure out how much room is left...
  */

  dstlen = strlen(dst);
  size   -= dstlen + 1;

  if (!size)
    return (dstlen);        /* No room, return immediately... */

 /*
  * Figure out how much room is needed...
  */

  srclen = strlen(src);

 /*
  * Copy the appropriate amount...
  */

  if (srclen > size)
    srclen = size;

  memcpy(dst + dstlen, src, srclen);
  dst[dstlen + srclen] = '\0';

  return (dstlen + srclen);
}
#endif /* !HAVE_STRLCAT */

#ifndef HAVE_STRLCPY
/*
 * '_cups_strlcpy()' - Safely copy two strings.
 */

size_t                  /* O - Length of string */
strlcpy(char       *dst,        /* O - Destination string */
              const char *src,      /* I - Source string */
          size_t      size)     /* I - Size of destination string buffer */
{
  size_t    srclen;         /* Length of source string */


 /*
  * Figure out how much room is needed...
  */

  size --;

  srclen = strlen(src);

 /*
  * Copy the appropriate amount...
  */

  if (srclen > size)
    srclen = size;

  memcpy(dst, src, srclen);
  dst[srclen] = '\0';

  return (srclen);
}
#endif /* !HAVE_STRLCPY */

然后,您可以使用它。好好享受。

于 2014-04-15T07:27:00.757 回答
4

strlcpy()它不是标准的 C 函数。

您可能也喜欢使用strncpy()或适当地memcpy()代替。

于 2013-08-31T10:46:09.087 回答
1

我在尝试编译代码时也遇到了这个错误,发现使用 Ubuntu 1604 如果我链接到-lbsd.

于 2017-08-11T18:14:44.447 回答