Writing and Compiling C Program in Linux Part 2: Using Custom Library

  • Instead of building custom function in a C program, we can include any custom function into a custom library. In this way, we could reuse the custom function between different program.
  • First, we maintain the same main(), but we remove all custom financial functions. Instead we included a statement included “fin.h” so that the compiler will search for the header file.
#include <stdio.h>
#include "fin.h"
int main (void)
{
double myrate;
int myterm;
double myprincipal;
double myreturn;
printf ("Please enter the following:\n");
printf ("Rate of return:(In decimal 50%% is 0.5)");
scanf ("%lf", &myrate);
printf ("\n");
printf ("Number of terms:(No decimals): ");
scanf ("%d", &myterm);
printf ("\n");
printf ("The principal amount: ");
scanf ("%lf", &myprincipal);
printf ("\n");
myreturn = tvm (myrate, myterm, myprincipal);
printf ("Your return after %d term is $%.2lf.\n", myterm, myreturn);
return 0;
}
  • Next, we create a header file (“fin.h”) that will include all financial functions in the future.
double tvm (double rate, int terms, double principal);
  • Finally, we create a new program call finfn.c (as in financial function). The custom function will be place here.
#include <math.h>
#include "fin.h"
double tvm (double rate, int terms, double principal)
{
double dn;
double pp;
dn = terms;
pp = pow (1+rate, dn);
return principal * pp;
}
  • The purpose splitting the program is such that tvm function can be reuse as a custom library in another program.
  • We can compile all the program #gcc -Wall tvm.c finfn.c -o tvm –lm
  • However, we don’t have to compile finfn.c every time of there is no changes.
  • One way is to create an object file during compilation instead of create executable.
  • We compile finfn.c first: #gcc -Wall -c finfn.c -o finlib.o
  • With the object file available, we can create another program tvm2 using the same tvm function:
#include <stdio.h>
#include "fin.h"
int main (void)
{
double rate = 0.025;
int term = 10;
double principal = 1000;
double result = 0;
result = tvm (rate, term, principal);
printf ("The return of $1000 investment with a rate of 2.5 percent in 10 years will give you $%.2lf.\n", result);
return 0;
}
  • Then we compile tvm2.c first before linking:
#gcc -Wall -c tvm2.c -o tvm2.o
  • We can link both program as follows:
#gcc tvm.o finlib.o -lm -o tvm
#gcc tvm2.o finlib.o -lm -o tvm2
  • In the example, we compile 2 programs using the custom function in one object file.
  • Alternatively, we can compile straight from tvm2.c to executable like below:
#gcc -Wall tvm2.c finlib.o -lm -o tvm2
Advertisements

2 Responses to Writing and Compiling C Program in Linux Part 2: Using Custom Library

  1. Brad says:

    Thanks, really helpful

  2. avto says:

    Thanks, it’s usefully

%d bloggers like this: