在 Swift (linux) 中链接 C 库及其支持库
Linking a C library and its supporting library in Swift (linux)
我想在 Swift 中使用 GNU 科学库,特别是我想使用 gsl_rng.h
中的例程。所以我基本按照https://github.com/apple/swift-package-manager/blob/master/Documentation/SystemModules.md(我用的是Linux,不是OS X)
我将模块创建为
module CGSL [system] {
header "/usr/include/gsl/gsl_rng.h"
link "gsl"
export *
}
但是,我无法构建我的程序,因为我收到了很多此类 undefined reference to 'cblas_dasum'
的消息。事实上,正如 GSL 的文档所述
To link against the library you need to specify both the main library
and a supporting CBLAS library, which provides standard basic linear
algebra subroutines. A suitable CBLAS implementation is provided in
the library libgslcblas.a if your system does not provide one. The
following example shows how to link an application with the library,
$ gcc -L/usr/local/lib example.o -lgsl -lgslcblas -lm
link -lgsl
和 -lgslcblas
我该怎么办?
为 libgslcblas
添加第二个 link
行就可以了:
module CGSL [system] {
header "/usr/include/gsl/gsl_rng.h"
link "gsl"
link "gslcblas"
export *
}
您可能还需要添加 link "m"
,即使我不必在我的盒子上这样做 (Ubuntu 14.04)。
我没有在 Swift 文档中找到关于此的具体建议,因此不得不做出有根据的猜测,但它奏效了。 Linux 上的 Swift 正在进行中,包管理器仅适用于 Swift 3.0 开发快照,Swift 3.0 是一种不稳定的、积极开发的最新语言版本。这种常见场景没有得到很好的记录这一事实应该让您了解该技术的成熟度。
作为包管理器的替代方案,您可能需要考虑使用桥接 header,如该问题的答案中所述:
Compile C code and expose it to Swift under Linux.
无论采用哪种方式,更大的挑战是从 Swift 调用 GSL API,因为 API 使用了很多 non-primitive 类型。要解决该问题,请考虑编写一个具有简化接口的 C 包装器,该接口可以很容易地从 Swift 调用。然后可以使用桥接 header 或系统模块调用包装器。
我想在 Swift 中使用 GNU 科学库,特别是我想使用 gsl_rng.h
中的例程。所以我基本按照https://github.com/apple/swift-package-manager/blob/master/Documentation/SystemModules.md(我用的是Linux,不是OS X)
我将模块创建为
module CGSL [system] {
header "/usr/include/gsl/gsl_rng.h"
link "gsl"
export *
}
但是,我无法构建我的程序,因为我收到了很多此类 undefined reference to 'cblas_dasum'
的消息。事实上,正如 GSL 的文档所述
To link against the library you need to specify both the main library and a supporting CBLAS library, which provides standard basic linear algebra subroutines. A suitable CBLAS implementation is provided in the library libgslcblas.a if your system does not provide one. The following example shows how to link an application with the library,
$ gcc -L/usr/local/lib example.o -lgsl -lgslcblas -lm
link -lgsl
和 -lgslcblas
我该怎么办?
为 libgslcblas
添加第二个 link
行就可以了:
module CGSL [system] {
header "/usr/include/gsl/gsl_rng.h"
link "gsl"
link "gslcblas"
export *
}
您可能还需要添加 link "m"
,即使我不必在我的盒子上这样做 (Ubuntu 14.04)。
我没有在 Swift 文档中找到关于此的具体建议,因此不得不做出有根据的猜测,但它奏效了。 Linux 上的 Swift 正在进行中,包管理器仅适用于 Swift 3.0 开发快照,Swift 3.0 是一种不稳定的、积极开发的最新语言版本。这种常见场景没有得到很好的记录这一事实应该让您了解该技术的成熟度。
作为包管理器的替代方案,您可能需要考虑使用桥接 header,如该问题的答案中所述: Compile C code and expose it to Swift under Linux.
无论采用哪种方式,更大的挑战是从 Swift 调用 GSL API,因为 API 使用了很多 non-primitive 类型。要解决该问题,请考虑编写一个具有简化接口的 C 包装器,该接口可以很容易地从 Swift 调用。然后可以使用桥接 header 或系统模块调用包装器。