ここでは、Unix や Linux の C 言語で共有ライブラリ ( .so ) を作成して使用する方法を掲載しています。
スポンサーリンク
共有ライブラリの作成
共有ライブラリ作成のサンプルコードです。関数名は ( test ) 、ファイル名は test.c および test.h とします。
test.h
#ifndef __TEST_H__
#define __TEST_H__
#if defined (__cplusplus)
extern "C" {
#endif
extern int test(int num);
#if defined (__cplusplus)
}
#endif
#endif /* __TEST_H__ */
test.c
#include <stdio.h>
#include "test.h"
int test(int num)
{
printf("%d\n", num);
return 0;
}
共有ライブラリをコンパイル
共有ライブラリをコンパイルして ( libtest.so ) を作成します。コンパイラには gcc を使用しています。
gcc -Wall -O2 -shared test.c -o libtest.so
共有ライブラリを呼び出す
上記で作成した共有ライブラリ ( libtest.so ) を呼び出します。実行ファイルのサンプルコード ( main.c ) とコンパイル例を示します。実行ファイル名は、sample としています。
main.c
#include <stdio.h>
#include <stdlib.h>
#include "test.h" // 共有ライブラリヘッダのインクルード
int main (int argc, char **argv)
{
/* 共有ライブラリの呼び出し */
test(5);
return EXIT_SUCCESS;
}
コンパイル
gcc -Wall -O2 -I./ main.c -o sample ./libtest.so
実行結果
作成した実行ファイルの実行結果は以下のとおりとなります。
./sample 5