Leo P. answered 08/19/23
Professional C tutor for the University of Central Florida
Both `.so` (shared object) and `.dylib` (dynamic library) are dynamic libraries, but they are used in different contexts, primarily based on the platform and the design/intent of the library. macOS primarily uses `.dylib`, but it also supports `.so` for compatibility, especially when dealing with software that's common to UNIX systems.
Here's a breakdown of the differences and some details on your questions:
1. **Conceptual Differences**:
- **.so**: This is the UNIX way of creating shared libraries. A shared object can have unresolved symbols, which get resolved at the runtime by the dynamic linker.
- **.dylib**: macOS's native dynamic library format. It contains more information than `.so` files, especially around versioning and dependency management. When a `.dylib` is loaded, all of its dependencies are loaded as well. It supports multi-architecture binaries using the `lipo` tool.
2. **Usage**:
- **.so**: You'd mainly come across `.so` files on macOS when dealing with software that's ported from UNIX or Linux. It's less common for native macOS development.
- **.dylib**: Preferred for native macOS development, especially if the library will be distributed or if you're building software that needs to interact with other macOS software in a dynamic way.
3. **Compilation**:
- For creating shared libraries on macOS:
- **.so**: You can still use `gcc -shared -fPIC -o libexample.so example.c`. However, remember that while macOS can produce `.so` files, they won't behave like typical shared objects on Linux. macOS treats them more like bundles, which are closer in behavior to static libraries.
- **.dylib**: Use `gcc -dynamiclib -o libexample.dylib example.c`.
- Also, for `.dylib` creation, you can set an "install name" which dictates the path where the library is to be found at runtime. This can be set with the `-install_name` option when creating the dylib.
4. **Linking**:
- When linking against a `.dylib`, the "install name" of the library is stored in the resulting binary (be it another library or an executable). At runtime, this is where the OS will look to load the library. You can view these with the `otool -L` command.
- `.so` files don't have this level of versioning or path dependency embedded.
5. **When to Use Which**:
- If you're writing software that's meant to be cross-platform and shared across UNIX-like systems, you might lean towards `.so`.
- For macOS-specific software or if you want to take advantage of macOS's dynamic library versioning and dependency management, prefer `.dylib`.
In general, unless you have a strong reason to use `.so` files on macOS (like a cross-platform build system that leans heavily on UNIX-style shared objects), you should opt for `.dylib` for native macOS development. It's more in line with the macOS ecosystem and tooling, and it offers features that can simplify versioning and distribution.