You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在含.c文件的Xcode静态库中添加Swift文件供Swift App调用

Swift静态库函数无法被外部App调用问题解决

问题场景

我创建了一个包含C文件的Xcode静态库项目,原本运行正常。之后通过Xcode「新建文件」添加了含Swift函数health_algo_test()的.swift文件,但引用该库的Swift App项目编译时提示:"Cannot find 'health_algo_test' in scope"。

相关代码与排查信息

App项目ViewController代码

override func viewDidLoad() 
{
    health_algo_test() // 报错位置
    . . .
}

静态库中的interface.swift代码

import Foundation
import UIKit
import os
    
func health_algo_test()
{
    print("health_algo_test...")
}

静态库符号检查(nm命令)

执行命令:

$ nm Debug-iphoneos/libproject_lib.a | grep health

输出结果:

0000000000000000 T _$s33project_libc16health_algo_testyyF

解决步骤

  1. 修改Swift函数的访问级别
    Swift默认函数访问级别是internal,仅能在当前模块内访问。要让外部App调用,必须显式声明为public:
import Foundation
import UIKit
import os
    
public func health_algo_test()
{
    print("health_algo_test...")
}
  1. 开启静态库的模块定义
    在静态库项目的Build Settings > Packaging中,将Defines Module设置为YES。这会让Xcode生成.swiftmodule文件,确保外部项目能识别库中的Swift接口。

  2. 正确导入静态库模块
    在App项目的代码开头,先导入静态库的模块(替换为你的库名称):

import project_lib

之后再调用health_algo_test()函数即可。

补充说明

nm命令输出的_$s33project_libc16health_algo_testyyF是Swift函数的名字修饰符号,其中project_lib是你的静态库模块名,说明函数确实已编译进静态库,但因访问权限或模块未导入的问题,导致App项目无法识别。

内容的提问来源于stack exchange,提问作者Doug Null

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 17:23:21