Home > OS >  How to link strlcpy in makefile in c- undefined reference to `strlcpy'
How to link strlcpy in makefile in c- undefined reference to `strlcpy'

Time:06-04

I'm new to C programming and Makefiles.

I have a function in my c code which uses strlcpy for copying string.

I'm not allowed to used #include <bsd/string.h> in my code so I have included #include <glib.h> . But while compiling makefile,

getting error: /usr/bin/ld: reg_maker.o: in function main': /home/reg_maker.c:66: undefined reference to strlcpy' /usr/bin/ld: /home/reg_maker.c:67: undefined reference to `strlcpy'

Below is the makefile I used :

OUT=reg_maker
OBJS=reg_maker.o
CC=gcc
IDIR = -I../../../include -I../../../include/xxxx  -I/usr/include/json-c/ -I/usr/lib/x86_64-linux-gnu/glib-2.0/include/ -I/usr/include/glib-2.0 -I/usr/include 
FLAGS= -c -g -Wall
LFLAGS= -lcrypto -ljson-c -lglib-2.0
all: $(OBJS)
    $(CC) -g $(OBJS) -o $(OUT) $(LFLAGS)
    
reg_maker.o:reg_maker.c
    $(CC) $(FLAGS) reg_maker.c $(IDIR)  $(LFLAGS)
clean:
    rm -f $(OBJS) $(OUT) reg_maker.bin`

I'm using ubuntu vm version- 20.04 , I have glib-2.0 library.

Could anyone please help me out what changes I have to make in make file to compile it with strlcpy

Thanks in advance

CodePudding user response:

According to the Ubuntu manual for strlcpy, the program should linked with libbsd (-lbsd) in overlay mode1 and include the <string.h> header.


1 The details of overlay mode, from libbsd(7):

The library can be used in an overlay mode, which is the preferred way, so that the code is portable and requires no modification to the original BSD code.

This can be done easily with the pkg-config(3) library named libbsd-overlay. Or by adding the system-specific include directory with the bsd/ suffix to the list of system include paths. With gcc this could be -isystem ${includedir}/bsd.

In addition the LIBBSD_OVERLAY pre-processor variable needs to be defined.

CodePudding user response:

Code using the BSD functions strlcpy and strlcat should be lined with the libbsd. If this library is not available on your system, you can add the source code for these functions in your own program:

#include <string.h>

size_t strlcpy(char *dst, const char *src, size_t n) {
    char *p = dst;

    if (n != 0) {
        for (; --n != 0; p  , src  ) {
            if ((*p = *src) == '\0')
                return p - dst;
        }
        *p = '\0';
    }
    return (p - dst)   strlen(src);
}

size_t strlcat(char *dst, const char *src, size_t n) {
    char *p = dst;

    while (n != 0 && *p != '\0') {
        p  ;
        n--;
    }
    if (n != 0) {
        for (; --n != 0; p  , src  ) {
            if ((*p = *src) == '\0')
                return p - dst;
        }
        *p = '\0';
    }
    return (p - dst)   strlen(src);
}
  • Related