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.