Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use gcc command with '-static'

When I tried to use gcc command to compile a test program with a static library 't1' which archive by myself.

The command I use to archive static library like this:

ar rcv libt1.a t1.o

Use the following command got An error:

gcc -L. -static -lt1 t.c -o t

ld: library not found for -lcrt0.o
clang: error: linker command failed with exit code 1 (use -v to see invocation)

But, If I remove '-static' like this:

gcc -L. -lt1 t.c -o t

It compile successfully. And I got the right result.

But I search a lot, find out other guys use '-static', and they do not get an error. So, please help me figure that.

like image 994
Richard Avatar asked Jun 01 '26 15:06

Richard


2 Answers

As explained in the comment, -static is not required to link against a static library of yours, but is used to instruct the compiler to link statically against the C (and C++, in case of g++) runtime libraries. This is not supported on OS X (link taken from the linked answer above), hence the error.

To link against your static library, just do as you did in the second command line, without specifying -static.

But I search a lot, find out other guys use '-static', and they do not get an error. So, please help me figure that.

They are probably working on Linux or Windows, where static linking against libc is supported (although even on Linux it brings its fair share of problems).

like image 53
Matteo Italia Avatar answered Jun 04 '26 00:06

Matteo Italia


ar rcv libt1.a t1.c

Typo? You don't normally want a C source file in a library.....

Clang is known to be a bit picky, especially with static libraries (Is this on MacOS, by any chance?) and will try and link to a non-existing runtime library - You can work around this by handing over the static library as an object file instead of a library like

gcc t.o libt1.a -o t

This should work.

like image 35
tofro Avatar answered Jun 04 '26 00:06

tofro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!