projects
- intro (due 20140124)
- "Hello, World!" (due 20140131)
- data types (due 20140207)
- Squares (due 20140214)
- Day of Week (due 20140221)
- Nikhilam (due 20140228)
- Multiply by 11 (due 20140307)
- Vertically and Crosswise (due 20140321)
projects
The ability to use programming libraries greatly enhances our capabilities, as we can use functions that others have created, instead of having to implement everything ourselves from ground up.
However, with the utilization of libraries, we need to provide additional input to the compiler so that all necessary data bits can be found.
We'll start by going through a simple example- square rooting.
In C, there is a math library (affectionately known as libm) that provides us with a set of math functions. Of them, sqrt() lets us calculate the square root.
From the man page (man 3 sqrt), we see the following:
NAME sqrt, sqrtf, sqrtl - square root function SYNOPSIS #include <math.h> double sqrt(double x); float sqrtf(float x); long double sqrtl(long double x); Link with -lm.
#include <stdio.h> #include <math.h> int main() { double a = 144, b = 0; b = sqrt(a); printf("The square root of %f is %f\n", a, b); return(0); }
If we try to compile this code, we should get the following compiler message:
lab46:~/src$ gcc -o math math.c /tmp/ccQNybzu.o: In function `main': math.c:(.text+0x32): undefined reference to `sqrt' collect2: ld returned 1 exit status lab46:~/src$
Note that there isn't a problem with the source code– that actually compiled cleanly. What it is having a problem with is that it does not know where to find the sqrt() function (because it isn't in the Standard C Library, which is the only library included by default).
If you recall from the manual page information, we have to link it against the math library (using the -lm option to the compiler). Let's go ahead and do that:
lab46:~/src$ gcc -o math math.c -lm lab46:~/src$
Success!
At this point we can run it and make sure it works (square root of 144? 12.)
lab46:~/src$ ./math The square root of 144.000000 is 12.000000 lab46:~/src$
For those up for a deeper understanding of how things connect together, in your terminal do a cd /lib, followed by an ls… /lib is a traditional location for libraries on UNIX systems… here you should be able to find:
Plus, by hunting around in the other “lib” directories (/usr/lib, /usr/local/lib, among others), you can find yet more libraries.
Note that there's a mechanism in place that aids the compiler in finding libraries if they are in these predefined locations. If you're using a library that is located elsewhere, you will need to also use the -L (note the CAPITAL L) option and specify a path.
Basically, to use a library, we need 2 things: