Basic Operations for Compiling with gcc and g++

Generally, compilation requires support from library files.

For example, static library files and dynamic library files.

On Windows, .lib files are static library files.

.dll files are dynamic library files.

The suffix for library files is as follows:

The suffix for static library files is .a.

The suffix for dynamic library files is .so.

The general process of compilation is:

Preprocessing — Compilation — Assembly — Linking.

These are the four steps.

Some code needs to be reused repeatedly.

For example, #include <stdio.h>.

This is actually a static library file.

To write a .c file or .cpp file:

g++ -c main.cpp

This generates an .o file.

It will create a main.o file.

Or:

gcc -c hello.c

This will also generate an .o file.

Following the naming convention for static libraries in Linux:

Static libraries are named as follows:

ar cr libhello.a hello.o

This command will definitely produce a libmain.a file.

Link the main.c file with the static library

to generate the executable file main:

g++ -o main main.cpp -static -lhello -L.

Note the trailing dot.

To run the executable file:

./main

Generating dynamic library files:

g++ -c -fPIC hello.cc -o hello.o

g++ -shared hello.o -o libhello.so

Using these commands, you can generate dynamic library files.

There is also a command for compiling and linking programs:

gcc -g -o hello hello.c

This allows the target file to include debugging information in the executable file.

Another command:

gdb hello

This is to debug the executable file using the GDB debugger.

This refers to the hello file generated above.

This file has no suffix.

In projects, static library files are reused repeatedly.

This is where common .h files come into play.

During execution, there is a complete copy each time.

This leads to a serious error:

Multiple redundant copies.

Dynamic libraries are not copied into the program during the linking phase.

Instead, they are loaded into memory for the program to use.

This solves the redundancy problem of static library copies.

The system only needs one dynamic library.

Different programs can access the system’s dynamic library copy in memory.

This saves memory.

Generating static and dynamic libraries:

hello.cc

hello.h

main.cc

Three files:

1. Generate static library:

g++ -o main main.cc -static -lhello -L.

2. Generate .o file from hello.cc:

g++ -c hello.cc

3. Link main.cc with the static library to generate the executable file:

g++ -o main main.cc -static -lhello -L.

Finally, six files will appear:

hello.cc

hello.h

hello.o

libhello.a

main

main.cc

4. Finally, execute the executable file:

./main

5. You can also generate dynamic libraries:

g++ -c -fPIC hello.cc -o hello.o

g++ -shared hello.o -o libhello.so

This generates the dynamic library file libhello.so.

Leave a Comment