Use GCC to create static and dynamic link libraries in Linux

Source: Internet
Author: User

The previous article introduced how to create a static Link Library and dynamic link library (http://blog.csdn.net/love_cppandc/article/details/8502773) in windows, this article describes how to create a static Link Library and dynamic link library in Linux.

In Linux, the static library file ends with. A and the dynamic library file ends with. So.

1. Static Link Library

First, create three files: 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;}

The command is as follows:

# Gcc-C static. c

This step is to generate the static. o file.

# Ar Cr libstatic. A static. o

This step generates a static Link Library. Note that the library name must start with Lib. This is required!

# Gcc-O test. C-L.-lstatic

In this step, link the static library with the test file. The. In-L. represents the current directory.

#./Test

Result 3


2. Dynamic Link Library

Create three files: 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;}

The command is as follows:

# Gcc-C dynamic. c

This step is to generate the dynamic. So file

# Gcc-shared-fpci-O libdynamic. so dynamic. So

This step is to generate a dynamic link library

# Gcc-O test. C-L.-ldynamic

This step links the dynamic library to the test file.

#./Test

Result 3

Conclusion: We found that the GCC commands for calling static and dynamic link libraries are the same, and it can be determined that when there is a static and dynamic library with the same name, give priority to dynamic libraries.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.