The ar tool under Ubuntu18.04 generates a static library/dynamic library and links it with the main function


foreword

Linux系统下,一些公用的函数我们常常生成一个函数库,方便其它函数调用、链接。静态库编译时会直接链接到主函数中,运行时就不需要了。动态库反之,在运行主函数时才会链接。


1. Use the Vim editor to prepare the sample program in advance

1、main.c

#include <stdio.h>
#include "sub.h"
int mian()
{
    
    
	int num1 = 3, num2 = 4;
	print_hello();
	printf("num1 x num2 = %.2f\n",sub(num1,num2));
	printf("num1 + num2 = %.2f\n",sub1(num1,num2));
	return 0;
}

insert image description here

2、sub.c / sub.h

#include "sub.h"
float sub(int num1, int num2)
{
    
    
	return (num1 * num2);
}
float sub1(int num1, int num2)
{
    
    
	return (num1 + num2);
}
#ifndef __SUB_H__
#define __SUB_H__

#include <stdio.h>

float sub(int num1, int num2);
float sub1(int num1,int num2);

#endif

3、hello.c / hello.h

#include "hello.h"
void print_hello(void)
{
    
    
	printf("hello word!\n");
}
#ifndef __HELLO_H__
#define __HELLO_H__
#include <stdio.h>

void print_hello(void);

#endif

2. Use gcc to generate a static library

1. Generate the corresponding .o file

gcc -c hello.c 生成对应的.o文件
gcc -c sub.c
ls -l 查看该目录下文件,看是否成功
insert image description here

2. Generate the corresponding .a file

ar -crv libmyhello.a hello.o
ar -crv libmysub.a sub.o
ls -l
insert image description here

3. Connect the static library to run the function

gcc main.c libmyhello.a sub.a -o main

insert image description here

./main
insert image description here

3. Use gcc to generate a dynamic library

1. Generate .so file

gcc -shared -fPIC -o libhello.so hello.o
gcc -shared -fPIC -o libsub.so sub.o
ls -l

insert image description here

2. Use the dynamic library to run the program

注意!!

When using the dynamic library, the program looks for the dynamic library under /usr/lib, and the dynamic library must be copied to this directory first

mv libhello.so /usr/lib
mv lib sub.so /usr/lib
gcc -o hello main.c -L. -lhello -lsub
ls -l
./main

insert image description here


Summarize

By practicing the generation and use of dynamic libraries/static libraries under gcc, I realized the charm of Linux and benefited a lot!

Guess you like

Origin blog.csdn.net/wer4567/article/details/127017472