ubuntugccstatic-linking

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).

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.