When I use the strlcpy function in c, the compiler gives me an error

Someone told me to use the strlcpy function instead of strcpy , like this

 #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); } 

and when I compile the file it gives me the following error:

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

notice: I installed MinGW (Minimalist GNU for Windows) and gcc version 4.7.2

What is the problem?

+6
source share
4 answers

undefined reference to `strlcpy '

This happens when the linker ( collect2 if you are using gcc) cannot find the definition of the function it is complaining about ( not the declaration but determining where the function code is defined).

In your case, this can happen because there is no shared object or library with strlcpy code for the link. If you are sure that there is a library with code, and you want to link it, consider specifying a library path with the -L<path_to_library> parameter passed to the compiler.

+4
source

strlcpy() not a standard C function.

Instead, you can use strncpy() or propably also memcpy() .

+4
source

Add this code to your code:

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

then you can use it. enjoy it.

+3
source

I also got this error while trying to compile the code and found that with Ubuntu 1604 the error will disappear if I contact -lbsd .

0
source

Source: https://habr.com/ru/post/952873/


All Articles