Command to create a static library in C

To create a static library in C, follow these steps:

  1. Create the source files: Write the functions and code that you want to include in your library. Save each function in a separate source file with a ".c" extension.

  2. Compile the source files: Use a C compiler to compile each source file into object files. This can be done using the command: gcc -c file1.c file2.c file3.c

  3. Create the object archive: Use the "ar" command to create an object archive file (.a) from the compiled object files. This can be done using the command: ar rcs libname.a file1.o file2.o file3.o

  4. "ar" is the command for the archiver.

  5. "rcs" are options for the archiver:

    • "r" is used to add the object files to the archive.
    • "c" is used to create the archive if it doesn't exist.
    • "s" is used to update the symbol table.
  6. "libname.a" is the name of the archive file you want to create.

  7. "file1.o", "file2.o", "file3.o" are the object files you want to include in the library.

  8. Verify the library creation: You can use the "ar" command with the "t" option to verify that the object files are included in the library. This can be done using the command: ar t libname.a

  9. "t" is the option to list the files in the archive.

  10. Link your program with the static library: To use the functions from the static library in your program, you need to link it during compilation. This can be done using the command: gcc -o program program.c -L/path/to/library -lname

  11. "-o program" specifies the output file name.

  12. "program.c" is the source file of your program.
  13. "-L/path/to/library" specifies the directory path where the library is located.
  14. "-lname" specifies the name of the library without the "lib" prefix and ".a" extension.

That's it! You have successfully created a static library in C.