Failure to link a program with gcc -static

289 views Asked by At

I'm trying to compile and link the following code with gcc:

#include <stdlib.h>

main()
{
    exit(0);
}

I'm using gcc -static -o exit exit.c

I get the following error:

/usr/bin/ld: cannot find -lc
collect2: ld returned 1 exit status

What does this mean and how can I fix this?

1

There are 1 answers

0
larsks On BEST ANSWER

In particular, it means it can't find the static version of the C library, because you are compiling with -static. This means that it can't use the standard shared library, typically something like /lib/libc.so.

In order to support building static binaries, you would need to install the appropriate static library (libc.a), which may or may not be available in pre-packaged format for your distribution. Under Fedora, this is available as the glibc-static package:

yum install glibc-static

With this package installed, I can build a static binary from your sample code without a problem:

$ gcc -static -o exit exit.c
$ file exit
exit: ELF 64-bit LSB executable, x86-64, version 1 (GNU/Linux),
statically linked, for GNU/Linux 2.6.32,
BuildID[sha1]=12c642ecc01622c623c2efa5efa7e23d73889808, not stripped

Other solutions include building the static C library yourself, or working with a smaller C library designed for embedding, such as uclibc or musl. These are smaller and typically more amendable to static linking. This would may also involve building the library yourself.