web-dev-qa-db-ja.com

cでstrlcpy関数を使用すると、コンパイラでエラーが発生します

誰かが私にこのように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

notice:インストールしましたMinGW(Minimalist GNU for Windows)and gcc version is4.7.2

何が問題ですか?

13
Ameen

`strlcpy 'への未定義の参照

これは、リンカ(gccを使用している場合はcollect2)が文句を言う関数の定義を見つけられない場合に発生します(not宣言またはプロトタイプが、 definition、関数のコードが定義されています)。

あなたの場合、リンク先のstrlcpyのコードを持つ共有オブジェクトまたはライブラリがないために発生する可能性があります。コードを含むライブラリが確実にあり、それに対してリンクする場合は、コンパイラに渡される-L<path_to_library>パラメータを使用してライブラリへのパスを指定することを検討してください。

7
NlightNFotis

このコードをコードに追加します。

#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 */

その後、それを使用することができます。楽しめ。

5
kangear

strlcpy()は標準のC関数ではありません。

代わりにstrncpy()またはおそらくmemcpy()を使用することをお勧めします。

4
alk

私もコードをコンパイルしようとしたときにこのエラーが発生し、Ubuntu 1604では、-lbsdとリンクするとエラーがなくなることがわかりました。

0
Niklas