Linux preliminary programming-creating a static function library

Source: Internet
Author: User

When we write a program need to call the library function, in the program code to add the header file containing the library function declaration, the compiler and linker according to the header file will be written by our program code and library function is located in the library file, build the executable file.

The simplest library of functions can be seen as a "collection" of some target files.

0. Creation of two function source files

1 #include <stdio.h>23void text1 (int  a)4{  5     printf ("%d", a);   6 }
View Code
1 #include <stdio.h>23void text2 (char *str)4 {5     6       printf ("%s", str); 7 }
View Code

1. Compile two function source files into the target file, respectively.

gcc -C text1.c text2.c

.

2. Create a header file with two function declarations

  

1 /* This is lib.h. It declares functions2*/34void text1 (int  ); 5 void Text2 (char *);
View Code

3. Write a test program, the program calls two test functions

1 #include <stdio.h>2"lib.h"34int Main () 5 {6       Text1 (1)'7       text2 ("Hello world\n")  89 }
View Code

4. Compile to target file, explicitly link the target file of the calling function

gcc -o text.o-c text.cgcc -o text text.o text1.o text2.o. /text

5. Assemble the generated two function target files together to generate a library of functions

  

ar crv libtext.a text1.o text2.o

6. Generating a table of contents for a function library

Ranlib LIBTEXT.A

7. The test program file to display the link function library to generate the executable (otherwise the compiler will go to the standard C library to find links)

You can also use-l to access the library because the library is not placed in the standard location-L path-l=lib

At this point we have completed a library of our own libtext.a, and tested it.

Linux preliminary programming-creating a static function library

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.