This command compiles and links your main program (main.c) with the library you created. It’s the culmination of all the previous work.
This process takes the source code, looks for the contract (.h), finds the binary code (.a) and produces the executable file.
gcc main.c
- Source File
- Tells the compiler to take this file as the starting point of the program
-o ../build/executable
- Output
- Tells GCC that the final product (the executable binary) should be called executable and saved in the ../build/ folder (go up one level, enter build)
- -I (capital letter i)
- These options are for the compilation phase. They tell GCC where to look for header (.h) files so it can verify that your code uses the functions correctly.
- Include Path
- Tells GCC to “Look for header files (.h) in the path ../../librariesc/src.” This allows main.c to find math_constants.h
- -L ../../librariesc/build
- Library Path
- Tells the linker: “Look for binary libraries (.a or .so) in the path ../../librariesc/build”
- -lmathconstants (lowercase letter L)
- Library Name
- Tells the linker: “Link this program with the library named libmathconstants” (The linker automatically adds the lib prefix and the .a or .so extension)
- Note that there is no space between the -l option and the library name, it is written all together
The .a file (the static library) is not unique in its location
The -L and -l arguments are not duplicating logic
-L: Specifies the path (directory) where to look for library files (.a or .so) for linking
-l: specifies the exact name of the library (without the lib prefix and without the .a or .so extension)
- Knowing where to look for it: This is provided by the -L option
- Knowing what it is called: This is provided by the -l option
- If you didn’t use -L, gcc would only look for the library in the standard system paths (/lib, /usr/lib, etc)
- The -L option simply adds a directory path to the list of places the linker should look
- The -l option (followed by the name) tells the linker which specific file to look for within the directories defined by -L and the default paths (Within each path, look for a file whose name matches the pattern lib + name of -l + .a or .so)
Without both, the process would fail: without -L, it wouldn’t find the directory; without -l, it wouldn’t know which file to look for
explanation
- Preprocessing: Expands the #include directives and finds the math_constants.h file using -I
- Compilation: Convert main.c to a temporary object file
- Link: Takes the temporary object file, goes to the -L folder, finds the libmathconstants.a file (thanks to -l), extracts the code from funcion(), connects it to the rest of the program, and combines it with the standard system libraries
- Output: The final product, the executable, is saved in the location specified by -o