这是一篇来自美国的系统编程代写
Building a program 101
- There are two phases of building a program, compiling and linking
- gcc is used to build the program
- ld can be used to link the program (or gcc)
Compiling a program
- You will run a command to compile gcc <source code> [options]
- Interesting options
- -c (tells the compiler to just generate the object files)
- -Wall (tells the compiler to show all warnings)
- -g (tells the compiler to generate debug information)
- -o <filename>.o (write output to file)
- An example
gcc hello.c -c -Wall -g -o hello.o
Linking a program
- You will run a command to link gcc <object files> [options]
- Interesting options
- -l<lib> (link with a library)
- -g (tells the compiler to generate debug information)
- -o <filename> (write output to file)
- An example,gcc hello.o goodbye.o -g -lmyexample -o hello
What is a “static” library?
- A library is a collection of related code and functions that are “linked” against a C program.
- The library “exports” “symbols”
- You program object code has “unresolved symbols”
- The linker pulls chunks of the library containing those symbols and places them into the program
- The program is done when all the pieces are resolved
- It is called “static” linking because this is done at link time
Building a static library
- A statically linked library produces object code that is inserted into program at link time.
- You are building an “archive” of the library which the linker uses to search for and transfer code into your program.ar rcs lib<libname>.a <object files>
- To run the command, use
- Library naming: with very few exceptions all static libraries are named library.a, e.g.,ar rcs libmyexample.a a.o b.o c.o d.o
- You link against the name of the library, not against the name of the file in which the library exists (see linking)
- A statically linked library produces object code that is inserted into program at link time.
- You are building an “archive” of the library which the linker uses to search for and transfer code into your program.
- To run the command, use
- Library naming: with very few exceptions all static libraries are named library.a, e.g.,
- You link against the name of the library, not against the name of the file in which the library exists (see linking)