LoginSignup
0

More than 5 years have passed since last update.

静的ライブラリを試す小さなメモ

Last updated at Posted at 2017-09-07

静的ライブラリは実行ファイルに同梱されるらしい。
リンク後にライブラリファイル削除しても実行できた。

コード

これを静的ライブラリに使う

sum.c
int sum(int a, int b){
        int r = a + b;
        return r;
}

ライブラリを使う側のコード
プロトタイプ宣言の部分はヘッダファイルを読み込む感じにするといいらしい

test2.c
#include <stdio.h>

int sum(int, int);

int main(int arg, char *argv[]){
        printf("hello\n");
        int n;
        n = sum(1, 4);
        printf("%d", n);
}

実行

まず静的ライブラリを作る

★オブジェクトファイル生成(この時点ではリンクはしない。sum.oができる)
# gcc -c sum.c
★静的ライブラリ作成(libsum.aができる)
# ar rusv libsum.a sum.o

で、できた静的ライブラリを使って実行ファイル作成

# gcc test2.c -o test2 -L . -lsum
# ./test2
hello
5

リンカのパスに通してみた場合

★パスを確認
# ldconfig -v
# cp libsum.a /usr/local/lib
★ -L で指定する必要がない
# gcc test2.c -o test2 -lsum

参考

ほとんど以下のサイトの抜粋

C: 静的ライブラリと共有ライブラリについて - CUBE SUGAR CONTAINER http://blog.amedama.jp/entry/2016/05/29/222739

[C言語] 共有ライブラリと静的ライブラリを整理する - Qiita http://qiita.com/edo_m18/items/b9765ff3313d5a13f82f

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
0