| Table of Contents | Previous Slide | Next Slide |
Software Development in the UNIX Environment
Sample C Code that Uses Libraries
This program contains two source files monte_pi_sprng.c and plot.c
/* Source file monte_pi_sprng.c *//* This program computes the value of PI using a Monte Carlo methodusing the SPRNG random number generator library. It computes PI for anincreasing amount of iterations and then makes a plot of the PI values computesversion the number of iterations. It uses the pgplot library to make the plot. */#include <stdio.h>#include <math.h>#include <string.h>#define SIMPLE_SPRNG /* simple interface */#include "sprng.h" /* SPRNG header file */#define SEED 23678951main(){int niter=0;double x,y;int i,j,count=0; /*# of points that lie in the 1st quadrant of the unit circle */double z;float pi[1000];float num_iter[1000];void plot();int ntrials = 200;/* initialize random numbers */init_sprng(SEED,SPRNG_DEFAULT);for (j= 0; j<ntrials; j++) {niter +=200;count=0;for ( i=0; i<niter; i++) {x = sprng();y = sprng();z = pow(x,2.)+pow(y,2.);if (z<=1) count++;}pi[j]=(double)count/niter*4;num_iter[j]=niter;}printf("Final estimate of pi is %g \n",pi[ntrials-1]);plot(0.,(double)niter,3.0,3.4,"# of Iterations","Computed PI Value", \"Computation of PI Using a Monte Carlo Method",ntrials,num_iter,pi);}
/* Source file plot.c *//* call pgplot library to plot data */#include <cpgplot.h>#include <stdio.h>void plot(double xmin,double xmax,double ymin,double ymax,\char* xlabel,char *ylabel,char* title,int npts,float *xpts,float *ypts) {int status;status = cpgopen("/XWINDOW");if (status <0) {fprintf(stderr,"Error opening X windows device from pgplot\n");exit(-1);}cpgenv(xmin,xmax,ymin,ymax,0,1);cpglab(xlabel, ylabel, title);cpgline(npts,xpts,ypts);cpgend();}
To compile this code:
cc -O3 -I /usr/local/lib/sprng/include -I
/usr/local/lib/pgplot -g -c monte_pi_sprng.c
cc -O3 -I /usr/local/lib/sprng/include -I
/usr/local/lib/pgplot -g -c plot.c
Explanation of compiling options
-O3: optimize to level 3 (aggressive)
-I : look for include files in the directories
/usr/local/lib/sprng/include and /usr/local/lib/pgplot
-g: produces debugging information for symbolic debugging
-c: create an object file from the named source file but don't
link it
To link this code:
cc -o monte_pi_sprng monte_pi_sprng.o plot.o
-L/usr/local/lib/sprng/lib -llcg -L/usr/local/lib/sprng/lib -lcpgplot
-lpgplot -lX11 -lftn -lm
Explanation of linking options
-L: look for library libllcg.a in the directory
/usr/local/lib/sprng/lib
-L: look for libraries libcpgplot.a and libpgplot.a in the
directory /usr/local/lib/sprng/lib
-lX11: include the X11 library libX11.so (a) in /usr/lib
-lm: include the math library libm.so (a) in /usr/lib