How to generate static library .a in linux

Static library production method:

Suppose there are the following three directories:
[root@localhost shumeipai]# ls
include lib main main.c src

(1) The main function of main.c contains the following content.
[root@localhost shumeipai]# cat main.c
#include <stdio.h>
#include “arithmetic.h”
int main()
{ printf(“addition operation=% d \n”,sum(10,20));

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

return 0;

}

(2) Include an arithmetic.h in the include directory
[root@localhost include]# pwd (display current location)
/home/shumeipai/include

The arithmetic.h header file contains the following:

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

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

#endif

(3) Include an arithmetic.c in the src directory and
its content is as follows:
[root@localhost src]# cat arithmetic.c
#include “arithmetic.h”

int sum(int a,int b)
{
int num=a+b;
return num;
}

int sub(int a,int b)
{
int num =a-b;
return num;
}

Step 1: Pack all the .c files that need to be compiled into a static library, except for the main main function, into .o files. The
packaging commands are as follows:

Execute in the src directory: gcc *.c -c -I …/include
This command can generate a .o file in the current directory

[root@localhost src]# gcc *.c -c -I …/include
[root@localhost src]# ls
arithmetic.c arithmetic.o

Step 2: Pack all the .o files to be packaged into a static library into the .a static library file through the packaging command ar

The packaging command is:
ar rcs libMytest.a *.o

This will generate a static library of .a in the src directory, the operation is as follows
root@localhost src]# ar rcs libMytest.a *.o
[root@localhost src]# ls
arithmetic.c arithmetic.o libMytest.a

Finally, move the libMytest.a file to the lib directory
[root@localhost src]# mv libMytest.a …/lib/

[root@localhost shumeipai]# cd lib/

[root@localhost lib]# ls
libMytest.a

Among them: libMytest.a named the static library name for itself, and Mytest named it for itself

Step 3: How to use the compiled static library?

Compile with gcc to generate an own executable program: 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 lib main.c myapp src

Note: If you cannot find the header file, you can specify the location of the header file with -I.

The nm command can view other .o file names contained in the static library,
so that you can make and use the static library file.

Guess you like

Origin blog.csdn.net/weixin_44881103/article/details/110954850
Recommended