Here is my small Swift and C project:
Package.swift
// swift-tools-version: 5.9
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "TestApp",
platforms: [.macOS(.v14), .iOS(.v13), .watchOS(.v6)],
products: [
.executable(name: "MyApp", targets: ["MyApp"]),
.library(name: "MySwiftLib", type: .static, targets: ["MySwiftLib"])
],
targets: [
.executableTarget(name: "MyApp",
cSettings: [
.headerSearchPath("../../.build/x86_64-apple-macosx/debug/MySwiftLib.build")
]/*,
linkerSettings: [
.unsafeFlags(["-Xlinker", "-rpath", "-Xlinker", "../../.build/x86_64-apple-macosx/debug/"]),
.linkedLibrary("MySwiftLib")
]*/
),
.target(name: "MySwiftLib")
]
)
Sources/MySwiftLib/MySwiftLib.swift
@_cdecl("mySwiftFunc")
public func mySwiftFunc() {
print("Hello from Swift")
}
Sources/MyApp/main.c
#include <stdio.h>
#include "MySwiftLib-Swift.h"
void main() {
puts("Hello World from C!");
mySwiftFunc();
}
-
First step: Building the static or dynamic library is not an issue:
swift build --product MySwiftLib
It produces./.build/x86_64-apple-macosx/debug/libMySwiftLib.a
and./.build/x86_64-apple-macosx/debug/MySwiftLib.build/MySwiftLib-Swift.h
when building a static library - and./.build/x86_64-apple-macosx/debug/libMySwiftLib.dylib
and./.build/x86_64-apple-macosx/debug/MySwiftLib.build/MySwiftLib-Swift.h
when building a dynamic library. -
The second step is to build the C app. I use
swift run
and it seems to requireobjc
:
/Users/olivier/dev/test_swift_lib/.build/x86_64-apple-macosx/debug/MySwiftLib.build/module.modulemap:1:8: error: module 'MySwiftLib' requires feature 'objc'
module MySwiftLib {
^
/Users/olivier/dev/test_swift_lib/Sources/MyApp/main.c:3:10: note: submodule of top-level module 'MySwiftLib' implicitly imported here
#include "MySwiftLib-Swift.h"
^
/Users/olivier/dev/test_swift_lib/Sources/MyApp/main.c:7:5: error: call to undeclared function 'mySwiftFunc'; ISO C99 and later do not support implicit function declarations [-Wimplicit-function-declaration]
mySwiftFunc();
^
2 errors generated.
[0/2] Compiling MyApp main.c