Linuxで静的ライブラリ.aを生成する方法

静的ライブラリの作成方法:

次の3つのディレクトリがあるとします。
[root @ localhost shumeipai] #ls
include lib main main.c src

(1)main.cのmain関数には、次の内容が含まれています。
[root @ localhost shumeipai] #cat main.c
#include <stdio.h>
#include“ arithmetic.h”
int main()
{ printf(“加算演算=%d \ n”、sum(10,20));

printf("减法运算 = %d \n ",sub(50,10));

return 0;

}

(2)インクルードディレクトリにarithmetic.hをインクルードします
[root @ localhost include]
#pwd (現在の場所を表示)/ home / shumeipai / include

算術.hヘッダーファイルには、次のものが含まれています。

#include <stdio.h>
#ifndef ARITHMETIC
#define ARITHMETIC

int sum(int a、int b);
int sub(int a、int b);

#endif

(3)srcディレクトリにarithmetic.cをインクルードし、
その内容は次のとおりです。
[root @ localhost src]#
catarithmetic.c #include“ arithmetic.h”

int sum(int a、int b)
{ int num = a + b; numを返します。}


int sub(int a、int b)
{ int num = ab; numを返します。}


ステップ1:メインのmain関数を除いて、静的ライブラリにコンパイルする必要のあるすべての.cファイルを.oファイルに
パックしますパッケージ化コマンドは次のとおりです。

srcディレクトリで実行します。gcc* .c -c-I…/ include
このコマンドは、現在のディレクトリに.oファイルを生成できます。

[localhostの@ルートSRC]#のGCCの* .c -c -I ... /含める
[ルートを@ localhostのソース]#lsの
arithmetic.c arithmetic.o

ステップ2:パッケージングコマンドarを使用して、静的ライブラリにパッケージ化するすべての.oファイルを.a静的ライブラリファイルにパックします。

パッケージ化コマンドは次の
とおりです。arrcslibMytest.a* .o

これにより、srcディレクトリに.aの静的ライブラリが生成されます。操作は次のとおりです
。root@ localhost src] #ar rcs libMytest.a * .o
[root @ localhost src]
#ls算術演算.olibMytest.a

最後に、libMytest.aファイルをlibディレクトリ
[root @ localhost src]#mvlibMytest.a…/ lib /に移動します。

[root @ localhost shumeipai] #cd lib /

[root @ localhost lib]
#ls libMytest.a

それらの中で:libMytest.aはそれ自体に静的ライブラリ名を付け、Mytestはそれ自体に名前を付けました

ステップ3:コンパイルされた静的ライブラリを使用するにはどうすればよいですか?

gccでコンパイルして、独自の実行可能プログラムを生成します:myapp

光線如下:
[root @ localhost shumeipai] #ls
include lib main.c src
[root @ localhost shumeipai] #gcc main.c lib / libMytest.a -o myapp -Iinclude
[root @ localhost shumeipai] #ls include libmain
。 c myapp src

注:ヘッダーファイルが見つからない場合は、-Iを使用してヘッダーファイルの場所を指定できます。

nmコマンドは、静的ライブラリに含まれている他の.oファイル名を表示
できるため、静的ライブラリファイルを作成して使用できます。

おすすめ

転載: blog.csdn.net/weixin_44881103/article/details/110954850