Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Linker cannot find strnstr() on Ubuntu with libbsd

To port some existing code from FreeBSD to Ubuntu (22.04) with the libbsd-dev package installed, I am encountering a problem in the linking phase: undefined reference to 'strnstr'. Code:

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

int main(int argc, char **argv) {

    char * ppl = "World citizens";

    char * s = strnstr(ppl, "c", strlen(ppl));

    printf("Hello, %s\n", s);
}

The command used for building and linking is: cc -lbsd test-strnstr.c. This command invokes gcc.

If called explicitly with clang (clang -lbsd test-strnstr.c) it works. It also compiles, links and runs fine on MacOS (without the ‘bsd/’ part in the first #include).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What can be the reason that it won’t link with the strnstr() in libbsd (and libbsd.a is installed /usr/lib/aarch64-linux-gnu/)?

>Solution :

Sometimes it’s because the order of libraries when linking with GCC. So I think you need to ensure that the order of libraries is correct.

Try cc test-strnstr.c -lbsd

Remember. the linker searches from left to right. The library that needs symbols must be first, then the library that resolves the symbol.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading