I'm trying to link to a static library on OS X. I used the -static
flag in the gcc command but I get the following error message:
ld_classic: can't locate file for: -lcrt0.o collect2: ld returned 1 exit status
I looked in the man pages and it reads something like:
This option will not work on Mac OS X unless all libraries (including libgcc.a) have also been compiled with -static. Since neither a static version of libSystem.dylib nor crt0.o are provided, this option is not useful to most people.
Is there another way to link to this static library?
A common case is to static link against a third user library while dynamically linking against the system frameworks and libraries, so your users don't need to install third party libs before using your program. If the library is dynamically linked against frameworks (as is often the case), it may still ship with a static .a, but it is not sufficient just to replace
-l<libname>
with/path/to/libname.a
because the .a will not have the dependencies in it. You will also have to dynamically link against those frameworks that your library was using.For example, say you want to write a program that uses the open source libusb without requiring your user to download and install libusb. Say you have a dynamically linked binary you built with this:
To statically link on OS X, the command looks like this (note the
-framework
arguments):To find what system frameworks and libraries you need to add, look at the third party dylib using otool:
which shows:
You can start by adding the frameworks, followed by the libraries one at a time and you will see the list of undefined reference errors shrink. Note you probably won't need to add every library, because some may be loaded as dependencies for the ones you explicitly added.
If you aren't sure where the dylib exists, build your program the original dynamic way (with -lusb-1.0), and run otool on it:
which gives:
Also, read the license of the library you are linking to.
I've been run into the same issue. Here is an example to work around:
STEP1: create files
myfunc1.c:
myfunc2.c:
and myfunc.c:
STEP2: create the lib
STEP3: link
Do not forget to type "-L."; dot indicates the current path.
Hope that helps.
In order to link to an archive library (sometimes also called static library), just add it to the link line:
The linker will search for libfoo.dylib, and then libfoo.a, which is all you need.
If you have both versions of the library, and want to link with an archive version in preference of the dynamic one, just specify the full path to the archive on the link line:
-Bstatic
seems to be a no-op on OS-X Lion - usedgcc -v
to confirm this.Regretfully, it's not supported. Some people reported it's possible to manually compile crt0 but nobody confirms it.