How GCC generates and calls static libraries

1. Introduction

This article mainly introduces how to use gcc to compile code to generate a static library, and call the operation steps of the static library to run.

Two, preparation

Flow chart of generating test feasibility file using add.c and main.c:
insert image description here

Contents of add.c file:

#include "add.h"

int add(int a, int b)
{
    
    
	printf("call add function: %d + %d = %d\r\n", a, b, a+b);
	return a+b;
}

Contents of add.h file:

#include <stdio.h>

int add(int a, int b);

Contents of the main.c file:

#include <stdio.h>
#include "add.h"

int main()
{
    
    
	int a=4, b=5;
	add(a, b);
	a++;
	b++;
	add(a, b);
	return 0;
}

Three, operation steps

3.1 Use add.c to generate libmath.a

Generate the corresponding target file:

gcc -c add.c 

Package the object files to generate a static library:

ar -crv libmath.a add.o

3.2 Call libmath.a static library to generate executable file test

Here are three methods, choose one of them.

Method 1: -L path -l algorithm library name

gcc -o test main.c -L. –lmath

Method 2: Directly add the library path

gcc main.c libmath.a -o test

Method 3: First generate main.o and then package it into an executable file

gcc -c main.c
gcc -o test main.o libmath.a

3.3 Run the executable file test

$ ./test.exe
call add function: 4 + 5 = 9
call add function: 5 + 6 = 11

In summary, the packaging and running of the static library have been completed.

Four, summary

This article mainly introduces how to generate a static library and how to call a static library for reference. Welcome to exchange and discuss together~

Guess you like

Origin blog.csdn.net/xuxu_123_/article/details/130966508