Commonly used gcc compilation instructions and operations

gcc is a toolchain.


1 Compile the source code into .o, only compile and not link.

gcc   -c output.o  source.c


2 Execute the link

gcc -o output source.c obj1.o obj2.o obj3.o

gcc -o output   source.o obj1.o obj2.o obj3.o

The linking process can also be performed with ld. but must specify

ld -o output  obj1.o obj2.o obj3.o -e entrypoint

-e specifies the entry point. Actually the default is _start



3 Merge two .o files into one .o

ld -r one.o another.o -o output.o

-r means generate relocatable .o files



4. Generate the .a file from the .o file using the ar command

ar rc liboutput.a   obj1 obj2 obj3 obj4

Merge two .a files. The way is to unpack and then generate

ar x lib1.a

ar x lib2.a

ar rc liboutpu.a *.o

 

5 Use the .o file to generate so

gcc -o liboutput.so -shared -fPIC obj1.o obj2.o obj3.o

-fPIC specifies that the compiled code is position independent. It is mainly to enable multiple instances to share a so file. Reduce memory footprint.



6 Use *.a when linking and *.so files when linking

-L specifies the path to the dynamic library -l specifies the name of the dynamic library

for example 

gcc -o main -L./ -ltest

Indicates to connect the libtest.so file in the current directory

For static libraries, you only need to add *.a files at the end

gcc -o main  libtest.a

Indicates the use of the static library libtest.a file






Guess you like

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