[Pitch] Cross-Platform C Library Access

In the earlier days of Swift, command-line and other apps that needed access to C library functions would simply add a one-liner import:

import Darwin

With the availability of Swift on a wide variety of platforms, there are now many different potential imports that could bring in the right libraries. On Linux, you'd import Glibc, and on Windows, you'd import ucrt. And now with Static Linux support, you might import musl. The "correct" import is becoming quite complicated and a lot of ceremony at the start of an otherwise innocuous Swift file:

#if os(macOS) || os(iOS)
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif os(Windows)
import ucrt
#else
#error(Unknown platform)
#endif

Yet the above code is missing support for important platforms like tvOS, watchOS, and visionOS, and will be broken on platforms like Wasm/WASI, FreeBSD, Android...

It would be interesting to consider if there's a better approach here, since packages that don't have exactly the right import formulation will break on inclusion with a static Linux app.

For example, could we offer a meta-import that is syntactic sugar for the above code snippet?

import stdlib

A quick review of open source code shows a wide variety of invocations, many of which are incorrect or at least dissimilar. Some assume Glibc, others check for os(musl), on Windows there is a variety of imports (ucrt, CRT, WinSDK). It feels like a good time to harmonize this for certain scenarios, rather than source code being bound to an assumption of what linked C libraries are available.

6 Likes
5 Likes

I feel like this is a step in the wrong direction, though. Using the C standard library should be a last-ditch effort, with effort being made into replicating anything you might want from it, within Foundation instead, using a more Swift-y API.

The more advanced low level stuff you might want aren't part of the standard library, anyway, and could vary from platform to platform. Even something like using locks/mutexes is very different from POSIX to, say, Windows. The #ifs don't end at the import block.

The dream would actually be for Swift programs to compile on an environment without a C compiler or runtime. With Foundation offering low level (i.e. not based on equivalent C functions) per-platform implementations of anything you might need, under a uniform API.

Making C standard libraries a standard in Swift would being going in the opposite direction to that.

4 Likes