2013-08-31 24 views
6

有人告訴我使用strlcpy函數而不是strcpy這樣當我使用是strlcpy函數在c compilor給我一個錯誤

#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的(簡約GNU適用於Windows)和GCC版本是4.7.2

什麼問題?

+0

@MitchWheat一個有效的點,但這不是爲什麼'ld'抱怨:-)) – cnicutar

+1

我沒有說這是。 :) –

+1

var1只有6個字符空間,您正試圖將6個字符字符複製到它。不是'你錯過了我們很好的''0'或者'你不想寫過去的var1緩衝區? – Abhineet

回答

4

undefined reference to `strlcpy'

這種情況發生在連接器(collect2如果你正在使用gcc)找不到抱怨(聲明或原型函數的定義,但定義,其中函數的代碼被定義)。

就你而言,可能會發生這種情況,因爲沒有與strlcpy的代碼鏈接的共享對象或庫。如果您確定存在帶有代碼的庫並且想要鏈接它,請考慮使用傳遞給編譯器的-L<path_to_library>參數指定庫的路徑。

4

strlcpy() ist不是標準的C函數。

您可能喜歡使用strncpy(),或者也可以使用memcpy()

+0

謝謝你的回答,但是當我在(cygwin,gcc 4.7.3)中編譯同一個文件時,它的工作原理 – Ameen

+0

@ameen:這些編譯器使用的庫可能會提供該函數作爲C標準的擴展。 – alk

3

將此代碼添加到您的代碼:

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

然後,你可以使用它。好好享受。

0

當我嘗試編譯代碼時,我也得到了這個錯誤,發現如果我使用Ubuntu 1604連接-lbsd,錯誤將消失。

相關問題