[SPM] Build a Swift project that contains a C-Header

Hello all,
I am trying to add SPM support to this project: https://github.com/myfreeweb/SwiftCBOR

I started with this Package.swift

// swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "SwiftCBOR",
    dependencies: [
    ],
    targets: [
        .target(
            name: "SwiftCBOR",
            dependencies: [ ],
            path: "SwiftCBOR”),
    ]
)

When building the project with swift build:

Compile Swift Module 'SwiftCBOR' (6 sources)
/Users/olivier/SwiftCBOR/SwiftCBOR/CBORDecoder.swift:148:30: error: use of unresolved identifier 'loadFromF16'
            return CBOR.half(loadFromF16(ptr))
                             ^~~~~~~~~~~
error: terminated(1): /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-build-tool -f /Users/olivier/SwiftCBOR/.build/debug.yaml main

The issue is SwiftCBOR relied on this C-header file at SwiftCBOR/SwiftCBOR.h They use a couple of C-functions to convert half precision float to float as suggested in this StackOverflow answer: https://stackoverflow.com/a/32960459/6267288

Any idea how to convert this project? Feel free to do it yourself and push your pull-request if you have the solution.

Thanks,
Olivier

/cc @Aciid

Hi,

SwiftPM doesn’t allow mixing C and Swift sources in the same targets. To import the C methods defined in your header file, you need a new target and then import that target instead. I was able to build your project after making the following changes:

  • Create Package.swift:
// swift-tools-version:4.0

import PackageDescription

let package = Package(
    name: "SwiftCBOR",
    dependencies: [
    ],
    targets: [
        .target(
            name: "CSwiftCBOR",
            dependencies: [],
            path: "CSwiftCBOR"),
        .target(
            name: "SwiftCBOR",
            dependencies: ["CSwiftCBOR"],
            path: "SwiftCBOR"),
    ]
)
  • Run the following commands:
$ mkdir -p CSwiftCBOR/include
$ touch CSwiftCBOR/shim.c       # This is needed by SwiftPM to detect this as a C target
$ mv SwiftCBOR/SwiftCBOR.h CSwiftCBOR/include/SwiftCBOR.h
$ Add `import CSwiftCBOR` in `SwiftCBOR/CBORDecoder.swift`
$ swift build