LoginSignup
10
8

More than 5 years have passed since last update.

[swift] Cライブラリーのモジュール化

Last updated at Posted at 2017-09-28

clangのmodule.modulemapファイルを用意することで、
cのライブラリーをモジュールとしてswiftソースファイルにimportすることができる。

ディレクトリ構造

以下のようにlibtestライブラリをモジュール化してmain.swiftファイルにimportする方法を説明します。

Sample/-*-main.swift
        |
        *-libtest/-*-lib/-*-libtest.a
                   |
                   *-inlucdes/-*-test.h
                               |
                               *-foo.h
                               |
                               *-bar.h

test.h
#include "foo.h"
#include "bar.h"
foo.h
int foo();
bar.h
int bar();

module.modulemapファイルを作成する

libtestディレクトリ配下に以下を作成する

module.modulemap
module libtest /*モジュール名*/ {
    header "include/test.h"
    export *
}

使用例

main.swift
import libtest

var fooNum: Int32 = libtest.foo()
var barNum: Int32 = bar() //モジュールを指定する必要はなし

main.swiftファイルは以下のようにしてビルドします。

$ swiftc -I ./libtest -L ./libtest/lib -ltest main.swift -o a.out
$ ./a.out #実行

NOTE:
* -I = モジュールの検索パスを指定
* -L = ライブラリーの検索パスを指定
* -ltest = libtest.aライブラリをリンクするように指定

関連

10
8
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8