Thursday, September 11, 2025
HomeiOS DevelopmentConstructing static and dynamic Swift libraries utilizing the Swift compiler

Constructing static and dynamic Swift libraries utilizing the Swift compiler


What the heck is a library?

A library) is a set of Swift elements that different functions can use.

Think about that you’re making a easy software to pluralize a string. It really works nice, you end the app and also you begin working in your subsequent one. In your subsequent software, you face the very same difficulty, you must print countable objects (e.g 2 bananas). What would you do? 🤔

The very first thing that may cross your thoughts is to repeat all of the supply code from the primary software into the second. Properly, this might work in fact, however what occurs in the event you uncover a bug within the pluralization part? Now you must repair the problem at two locations, since you’ve got simply duplicated all the stuff. There should be a greater manner… 🧠

Luckily pc programmers confronted the very same difficulty, so that they invented shared libraries. A shared library is a particular type of binary part that you need to use in your important software. This fashion you possibly can outsource Swift code right into a separate file (or bunch of information), throw in some entry management to permit different apps to make use of public strategies and name capabilities out of your library and right here we go, we simply shared our frequent code between our functions.

Oh wait, there’s a bug within the lib, how can I repair it? Properly, that is the place issues get a bit sophisticated, however don’t be concerned an excessive amount of, I will attempt to clarify the way it works. So, final time, you already know, once we talked concerning the Swift compiler and linker, I discussed, that they will resolve dependencies in your program. While you use a library you possibly can select between two approaches.

  • static linking
  • dynamic linking

Static linking signifies that the supply code contained in the library can be actually copy-pasted into your software binary. Dynamic linking however signifies that your library dependencies can be resolved at runtime. By the best way, you must resolve this upfront, since you must construct both a static or a dynamic library. Huhh? Okay, let me do this once more… 🙃

The static library strategy is extra easy. You may simply construct a static library utilizing the compiler (you will see how one can make one afterward), then you possibly can import this library inside your software supply (import MyLibrary). Now while you compile the primary app, you must inform the compiler the placement of your static (binary) library, and the publicly accessible objects (headers or module map) which might be accessible to make use of. This fashion when your app consists the symbols from the lib (lessons, strategies, and so forth) will be copied to the primary executable file). While you run the app, required objects can be there already contained in the binary file, so you possibly can run it as it’s.

The primary distinction between a static and a dynamic library is that you do not copy each required image to the executable software binary while you use a dylib file, however a number of the “undefined” symbols can be resolved at runtime. First you must construct your library as a dynamic dependency utilizing the Swift compiler, this can produce a dynamic (binary) library file and a module map (header information). While you make the ultimate model of your app, the system will put references of the dynamic library to your executable as a substitute of copying the contents of the dylib file. If you wish to run your software you must make it possible for the referenced dynamic library is on the market to make use of. The working system will attempt to load the generated dylib file so the applying resolves the symbols primarily based on the reference pointers. 👈

Ought to I select dynamic or static linking?

Properly, it will depend on the atmosphere. For instance the Swift Bundle Supervisor prefers to make use of static linking, however Xcode will attempt to construct SPM packages as dynamic dependencies. You can even explicitly inform SPM to construct a static or dynamic library, however in many of the instances you must keep on with the automated worth, so the system can construct the correct module dependency for you.


import PackageDescription

let package deal = Bundle(
    identify: "MyLibrary",
    merchandise: [
        
        .library(name: "MyLibrary", targets: ["MyLibrary"]),
        
    ],
    targets: [
        .target(name: "MyLibrary", dependencies: []),
    ]
)

By the best way in case you are confused sufficient, I’ve an article for learners about Swift packages, modules, frameworks and the instruments that makes this complete dependency administration potential. You need to undoubtedly have a look, it is a some form of a deep dive into FAT frameworks, however the first a part of the article is filled with helpful definitions and introductions to numerous instructions.

Again to the unique query: static vs dynamic? Do you keep in mind the bug within the library that we’ve got to repair? If you happen to use a static library you must rebuild all of the apps which might be relying on it (they should be linked with the mounted library in fact) with a view to make the problem disappear. 🐛

Since a dynamic library is loaded at runtime and the symbols usually are not embedded into the applying binary, you possibly can merely construct a brand new dylib file and change the previous one to repair the bug. This fashion all of the apps which might be referencing to this dependency can have the repair without cost. There is no such thing as a have to recompile everyting, besides the defective code within the framework itself. 💪

It’s also price to say that the ultimate app measurement is smaller while you use a dylib.

Okay, however why ought to I ever use static linking if dylibz are so cool? The reality is that generally you wish to encapsulate every thing right into a single binary, as a substitute of putting in plenty of different dylib information into the system. Additionally what occurs if one thing deletes a dylib that your app would require to work flawlessly? That’d suck for certain, particularly if it’s a mission-critical script on a server… 😳

Hopefully, I over-explained issues, so we will begin constructing our very first static library.

Compiling a static Swift library

Do you continue to have that little Level struct from the earlier tutorial? Let’s construct a static library from that file, however earlier than we accomplish that, we’ve got to explicitly mark it as public, plus we’d like a public init methodology so as to have the ability to create a Level struct from our software. You already know, in Swift, entry management permits us, programmers, to cover particular elements of a library from different builders.

public struct Level {
    public let x: Int
    public let y: Int

    public init(x: Int, y: Int) {
        self.x = x
        self.y = y
    }
}

Now we’re able to construct our static library primarily based on this single level.swift supply file. As I discussed this earlier than, we’d like a binary file and a module map file that comprises the publicly accessible interface for the lib. You should utilize the -emit-library flat to inform the Swift compiler that we’d like a binary library file plus utilizing the -emit-module parameter will produce a Swift module information file with all of the API and docs wanted for different modules. By default the compiler would emit a dylib (on macOS at the least), so we’ve got to make use of the -static flat to explicitly generate a static dependency. 🔨

swiftc level.swift -emit-module -emit-library -static

The command above ought to produce 4 new information:

  • libpoint.a – The binary static library itself
  • level.swiftdoc – Documentation for the module (binary format)
  • level.swiftmodule – Information concerning the module, “Swift header file”
  • level.swiftsourceinfo – Supply info file

Transfer these information inside a lib folder, so it’s going to be less difficult to work with them. That is actually it, we have simply created a working static library, however how can we use it to hyperlink them in opposition to our important software? 🤔

Initially, we’ve got to import our newly created module contained in the important.swift file if we wish to use the objects (in our case the Level struct) from it. By the best way you possibly can add a customized module identify to your library in the event you use the -module-name [name] argument with the earlier swiftc command.

import level

let p = Level(x: 4, y: 20)

print("Good day library!", p.x, p.y)

So, all of our library information are situated in a lib folder, and our default module identify is level (primarily based on our single enter file). We will use the swiftc command once more, to compile the primary file, this time we use the -L flag so as to add a library search path, so the compiler can find our binary libpoint.a file. We additionally must set a search path for imports, the -I property will assist us, this manner the general public API (headers) of the module can be accessible in our supply file. The very very last thing that we’ve got to append to the tip of the command is the -l[name] flag, this specifies the library identify we wish to hyperlink in opposition to. Watch out, there is no such thing as a house in between the -l and the identify worth! ⚠️

swiftc important.swift -L ./lib/ -I ./lib/ -lpoint

# run the app
./important
# Good day library! 4 20

Voilá, we have simply separated a file from the primary software through the use of a static dependency. 👏

Compiling a dynamic Swift library

In principle, we will use the identical code and construct a dynamic library from the level.swift file and compile our important.swift file utilizing that shared framework. We simply drop the -static flag first.

swiftc level.swift -emit-module -emit-library

This time the output is barely totally different. We have a libpoint.dylib binary as a substitute of the libpoint.a, however all the opposite information look similar. Extension my fluctuate per working system:

  • macOS – static: .a, dynamic: .dylib
  • Linux – static: .so, dynamic: .dylib
  • Home windows – static: .lib, dynamic: .dll

So we’ve got our dylib file, however the true query is: can we construct the primary.swift file with it?

swiftc important.swift -L ./lib/ -I ./lib/ -lpoint

# run the app
./important
# Good day library! 4 20

Now rename the libpoint.dylib file into libpoint.foo and run the primary app once more.

./important

# dyld: Library not loaded: libpoint.dylib
#   Referenced from: /Customers/tib/./important
#   Purpose: picture not discovered
# zsh: abort      ./important

Whoops, looks as if we’ve got an issue. Don’t be concerned, that is the anticipated output, since we renamed the dynamic library and the applying cannot discover it. When the loader tries to get the referenced symbols from the file it appears to be like up dynamic libraries at a number of totally different locations.

  • The listing you specified by means of the -L flag (./lib/).
  • The listing the place your executable file is (./)
  • The /usr/lib/ or the /usr/native/lib/ directories

For the reason that /usr/lib/ listing is protected by the well-known SIP “guard”, you must ship your dylib information subsequent to your executable binary, or alternatively you possibly can set up them below the /usr/native/lib/ folder. Sadly, this lookup technique can result in all form of points, I actually do not wish to get into the small print this time, however it could result in compatibility and safety points. 🤫

The excellent news is that now in the event you change one thing within the dylib, and also you merely rebuild & change the file you then run the ./important once more (with out recompiling), the altered dynamic library can be used. Simply attempt to put a print assertion into the init methodology of the Level struct…

Abstract

Actually, I might relatively go along with a static library in many of the instances as a result of utilizing a static library will assure that your software has each needed dependency embedded into the binary file.

In fact dynamic libraries are nice in case you are the creator of a generally used framework, such the Swift commonplace library, Basis or UIKit. These modules are shipped as shared libraries, as a result of they’re large and virtually each single app imports them. Simply give it some thought, if we might hyperlink these three frameworks statically that’d add rather a lot to the scale of our apps, plus it might be manner more durable to repair system-wide bugs. That is the rationale why these packages are shipped as shared libz, plus Apple can provides us a promise that these elements will all the time be accessible as a part of the working system. 😅

Anyhow, there are some instruments that you need to use to change library loader paths, I will inform you extra about this subsequent time. It should be a extra superior matter together with totally different languages. I’ll present you how one can construct a library utilizing C and how one can name it utilizing Swift, with out SPM. 🤓

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments