how to create a static library in C:

  • First, create a source file for your library. Let’s call it mylib.c. Here’s an example of what the file might contain:

#include <stdio.h>

void say_hello() {

printf(“Hello from my library!\n”);

}

  • Compile the source file into an object file:

gcc -c -Wall -Werror mylib.c -o mylib.o

The -c flag tells the compiler to stop after compiling, and not to attempt to link the object file. The -Wall and -Werror flags enable compiler warnings and treat them as errors. Finally, we specify the input and output files.

  • Create the static library using ar:

ar rcs libmylib.a mylib.o

The r flag tells ar to add the object file to the archive if it isn’t already present, and c creates the archive if it doesn’t exist. The s flag updates the symbol table to include all symbols in the object file, which is necessary for linking.

That’s it! You now have a static library that can be linked directly into a C program. To use the library, you would include the header file and link against the library:

#include “mylib.h”

int main() {

say_hello();

return 0;

}

  • gcc -Wall -o myprogram myprogram.c -L. -lmylib

The -L. flag tells the linker to look for the library file in the current directory, and -lmylib specifies that we want to link against libmylib.a.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s