Give an example: how to write dynamic and static link libraries and reference them in C programs. And how the link library works
Dynamic link library
Compile
The gcc compiler can compile code into a DLL dynamic link library in Windows. However, it should be noted that in Windows, the naming convention of dynamic link libraries is different from systems such as Linux. In Windows, the naming convention of dynamic link libraries is usually <name>.dll
or lib<name>.dll
, where <name>
is the name of the dynamic link library.
In addition, specific compilation options and link options need to be used when compiling dynamic link libraries, such as:
- Use the
-shared
option to specify compilation as a dynamic link library. - Use the
-fPIC
option to generate position-independent code so that dynamic link libraries can be loaded correctly at runtime.
First write the code of the library. Suppose we define a Hello function in the library:
Here is a simple command example that demonstrates how to use the gcc compiler to compile code into a DLL dynamic link library in Windows:
This will generate a dynamic link library named hello.dll
.
If you are on a Unix-like platform, the dynamic link library convention is different from Windows, and it uses the so
suffix. So the compilation command can be written as follows:
Usage
To use a dynamic link library, you must first give the header file of this library: define the relevant declarations in the library. We write a header file for the Hello library:
In Windows, introducing a dynamic link library requires the help of library functions defined in Windows.h provided by the Windows SDK
If it is a Unix-like platform, it can be referenced like this
Then compile the target program
Static link library
Compile
First write the code of the library. Suppose we define a Hello function in the library:
Here is a simple command example that demonstrates how to use the gcc compiler to compile code into a static link library:
First, compile the hello.c
code into an object file
Then use the ar
command to package the target file into a static library.
Executable on Windows systems
Executable on Unix-like systems
Usage
Similarly, using a static link library also requires writing a header file for the library
Reference library functions in the main program
Then add the link option to the hello library when compiling the main program.