[英]How to build a local C library as a Static Library and link with Swift?
As the title suggests, I am having a bit of trouble creating a static library from C code and having it used in a Swift project.正如标题所暗示的那样,我在从 C 代码创建静态库并将其用于 Swift 项目时遇到了一些麻烦。
Here is the make process for the C-Code:这是 C 代码的 make 过程:
make
# Making the static library
clang -c Sources/nuklear.c -o nuklear.o
clang -c Sources/test.c -o test.o
libtool -static nuklear.o test.o -o libNuklear.a
cp libNuklear.a /usr/local/lib
❯ ls /usr/local/lib | grep Nuk
libNuklear.a
Here is the error:这是错误:
swift build -Xlinker -L/usr/local/lib
'CNuklear' /Users/pprovins/Projects/CNuklearTest/.build/checkouts/CNuklear: warning: system packages are deprecated; use system library targets instead
ld: warning: Could not find or use auto-linked library 'libNuklear'
Undefined symbols for architecture x86_64:
"_test_doit", referenced from:
_main in main.swift.o
ld: symbol(s) not found for architecture x86_64
[0/1] Linking CNuklearTest
The error suggests the library cannot be found or the library is not usable (unable to determine which).该错误表明找不到库或库不可用(无法确定是哪个)。
Running nm
on libNuklear.a
reveals:在libNuklear.a
上运行nm
显示:
libNuklear.a(test.o):
U _printf
0000000000000000 T _test_doit
It appears the symbols do exist, so I am leaning toward the possibility of it being an issue finding the library to link against so I shall describe my bridging process next.看起来符号确实存在,所以我倾向于找到要链接的库的问题,所以接下来我将描述我的桥接过程。 The C-Code is placed in a system-library module/package separate from the executable being built. C 代码放置在与正在构建的可执行文件分开的系统库模块/包中。 It contains a bridging header and package definition.它包含一个桥接头和包定义。 Here is the module.modulemap
definition:这是module.modulemap
定义:
module CNuklear [system] {
header "Includes/CNuklear.h"
link "libNuklear"
export *
}
The bridging header ( CNuklear.h
):桥接头( CNuklear.h
):
#import "Includes/nuklear.h"
#import "Includes/test.h"
I currently make the static library, then attempt to build the swift executable;我目前制作静态库,然后尝试构建 swift 可执行文件; however, it is having trouble linking against the static library I have made.但是,它在链接我创建的静态库时遇到问题。 Here is how I am attempting to include and execute the code in main.swift
:这是我尝试在main.swift
包含和执行代码的main.swift
:
import CNuklear
test_doit()
print("Hello, world!")
Is there a way to further debug the issue with linking that I am having?有没有办法进一步调试我所拥有的链接问题? Thanks in advance!提前致谢!
In the module.modulemap
file:在module.modulemap
文件中:
If the static library being built is named libNuklear.a
, the link
specification for the module must be:如果正在构建的静态库名为libNuklear.a
,则模块的link
规范必须是:
module CNuklear [system] {
header "Includes/CNuklear.h"
link "Nuklear"
export *
}
You must also run swift build
with -Xlinker -L/usr/local/lib
or -Xlinker -L/dir/which/lib/resides
您还必须使用-Xlinker -L/usr/local/lib
或-Xlinker -L/dir/which/lib/resides
-Xlinker -L/usr/local/lib
运行swift build
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.