Create static library for C program in Linux

Consider your C program has three files, which are addSub.c, mulDiv.c and main.c

addSub.c : 
int add(int x, int y)
{
    return x + y;
}
 
int sub(int x, int y)
{
        return x - y;
}
mulDiv.c : 
int mul(int x, int y)
{
    return x * y;
}
 
int div(int x, int y)
{
        return x / y;
}
main.c : 
#include <stdio.h>
 
int main(int argc, char *argv[])
{
    printf("%d\n", add(10, 15));
    printf("%d\n", sub(50, 15));
    printf("%d\n", add(10, 3));
    printf("%d\n", add(100, 4));
    return 0;
}

1 . Compile and create object file for addSub.c and mulDiv.c 
gcc -c addSub.c mulDiv.c -Wall
2.  Create static library( liboperation.a ) for compiled files 
ar -cvq libopeartion.a addSub.o mulDiv.o
3.  We can list the available files from library file using following
ar -t libopeartion.a
4. Compile the main program with linking the library 
gcc -o output main.c libopeartion.a
5. Run the created output executable file
./output 

No comments:

Post a Comment