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:
clang -lusb-1.0 main.c -o myprogram
To statically link on OS X, the command looks like this (note the -framework
arguments):
clang -framework CoreFoundation -framework IOKit main.c /path/to/libusb-1.0.a -o myprogram
To find what system frameworks and libraries you need to add, look at the third party dylib using otool:
otool -L /usr/local/opt/libusb/lib/libusb-1.0.0.dylib
which shows:
/usr/local/opt/libusb/lib/libusb-1.0.0.dylib:
/usr/local/opt/libusb/lib/libusb-1.0.0.dylib (compatibility version 2.0.0, current version 2.0.0)
/usr/lib/libobjc.A.dylib (compatibility version 1.0.0, current version 228.0.0)
/System/Library/Frameworks/IOKit.framework/Versions/A/IOKit (compatibility version 1.0.0, current version 275.0.0)
/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation (compatibility version 150.0.0, current version 1348.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1238.0.0)
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:
clang -lusb-1.0 main.c -o myprogram
otool -L myprogram
which gives:
myprogram:
/usr/local/opt/libusb/lib/libusb-1.0.0.dylib (compatibility version 2.0.0, current version 2.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1238.0.0)
Also, read the license of the library you are linking to.
ld
command that actually does this. – Maihem