3

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.

Richard
  • 35
  • 1
  • 4
  • Possible duplicate of http://stackoverflow.com/questions/844819/how-to-static-link-on-os-x – tofro Mar 23 '16 at 07:10
  • 1
    `-static` is not needed to link against static libraries, but to link statically against the C/C++ runtime libraries, which AFAICT is not what you are trying to achieve; you can do without it. By the way, why are you putting a `.c` file into a static library? – Matteo Italia Mar 23 '16 at 07:13
  • @MatteoItalia that's a write mistake, what I mean is "t1.o". – Richard Mar 23 '16 at 07:30
  • the `gcc` linker retrieves/processes command line arguments left to right, So I am surprised that either method worked. I.E. the `-L` and `-l` should be at the end of the line. – user3629249 Mar 23 '16 at 21:03

2 Answers2

4

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

Community
  • 1
  • 1
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
1

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.

tofro
  • 5,640
  • 14
  • 31
  • It's a write mistake, what I mean is "t1.o", and I truly work on MacOS.The command you give is work as well, but I am just curious why the '-static' make an error. – Richard Mar 23 '16 at 07:35