Generation and use of static library .a and .so library files under Linux

Edit four files: A1.c A2.c Ah test.c

A1.c:

#include <stdio.h>

void print1(int arg){
printf("A1 print arg:%d\n",arg);
}

A2.c:

#include <stdio.h>

void print2(char *arg){
printf("A2 printf arg:%s\n", arg);
}

A.h

#ifndef A_H
#define A_H
void print1(int);
void print2(char *);
#endif

test.c:

#include <stdlib.h>
#include "A.h"

int main(){
print1(1);
print2("test");
exit(0);
}


1. Generation and use of static library .a files.

1.1. Generate target file (xxx.o)

---> gcc -c A1.c A2.c


1.2. Generate static library .a file

---> ar crv libafile.a A1.o A2.o



1.3. Use the .a library file to create an executable program (if this method is adopted, it is necessary to ensure that the generated .a file and the .c file are stored in the same directory, that is, both are in the current directory)

---> gcc -o test test.c libafile.a

---> ./test


2. Generation and use of shared library .so files

2.1. Generate the target file (xxx.o) (" -fpic " must be added to generate the .o file here (small mode, less code), otherwise an error will occur when generating the .so file)

---> gcc -c -fpic A1.c  A2.c

2.2. Generate shared library .so file

---> gcc -shared *.o -o libsofile.so

2.3. Use the .so library file to create an executable program

---> gcc -o test test.c libsofile.so

---> ./test

An error was found:

./test: error while loading shared libraries: libsofile.so: cannot open shared object file: No such file or directory

Run ldd test to check the link

ldd test
    linux-vdso.so.1 => (0x00007fff0fd95000)
    libsofile.so => ​​not found
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f937b5de000)
    /lib64/ld- linux-x86-64.so.2 (0x0000563f7028c000)


found that the corresponding .so file could not be found.

This is due to the corresponding settings set by the Linux system itself, that is, it only searches for the corresponding .so file under /lib and /usr/lib , so the corresponding so file needs to be copied to the corresponding path.

--->sudo cp libsofile.so /usr/lib

Execute ./test again to run successfully.

---> ./test


At the same time, you can use gcc -o test test.c -L. -l name directly to use the corresponding library file

in,

        -L.: Indicates that in the current directory, you can define the path path by yourself, that is, use -Lpath.

      -lname:name: The name of the corresponding library file (except lib), that is, if libafile.a is used, the name is afile; if libsofile.so is used, the name is sofile).


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325996239&siteId=291194637
Recommended