linux下用gcc建立靜態連結庫和動態連結程式庫

來源:互聯網
上載者:User

上一篇文章介紹了在windows下如何建立靜態連結庫和動態連結程式庫(http://blog.csdn.net/love_cppandc/article/details/8502773),這一篇介紹一下在linux下如何建立靜態連結庫和動態連結程式庫。

在linux下,靜態庫檔案是.a結尾,動態庫檔案是.so結尾。

1.靜態連結庫

首先建立3個檔案:static.h static.c test.c

static.c

int add( int a, int b ){return a + b;}

static.h

#ifndef LIB_H#define LIB_Hint add(int a,int b);#endif

test.c

#include <stdio.h>#include "static.h"int main(){printf( "%d\n", add(1,2) );return 0;}

命令如下:

# gcc -c static.c

這一步是產生static.o檔案

# ar cr libstatic.a static.o

這一步是產生靜態連結庫,特別需要注意的是庫名字必須是lib開頭,這個是必須的!

# gcc -o test test.c -L. -lstatic

這一步是將static庫與測試檔案test進行連結, -L.中的.代表目前的目錄

# ./test

結果為3


2.動態連結程式庫

建立三個檔案:dynamic.c dynamic.h test.c

dynamic.c

int add( int a,int b ){return a + b;}

dynamic.h

#ifndef DYNAMIC#define DYNAMICint add( int a,int b);#endif

test.c

#include <stdio.h>#include "dynamic.h"int main(){printf( "%d\n",add(1,2) );return 0;}

命令如下:

# gcc -c dynamic.c

這一步是產生dynamic.so檔案

# gcc -shared -fPCI -o libdynamic.so dynamic.so

這一步是產生動態連結程式庫

# gcc -o test test.c -L. -ldynamic

這一步是將dynamic庫與測試檔案test進行連結

# ./test

結果為3

總結:我們發現,調用靜態連結庫和動態連結程式庫的gcc命令完全一樣,並且可以確定的是,當存在同名的靜態庫和動態庫時,優先調用動態庫。



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.