Suppose we start with something one step up from "Hello world." We want to use the C math library. We do something like this in

`test.c`

:The math library defines constants like

`M_PI`

and functions like `sqrt`

. It works:Now, we want to define our own function for doing square roots. We have our own super-duper code in

`mymath.c`

. (I should've done Newton's method or something, but I was in a hurry):`float mysqrt(float n) { return 10.2; }`

and

`mymath.h`

:`float mysqrt(float n)`

;We add an appropriate call in

`test.c`

:` printf("%3.2f\n", mysqrt(M_PI));`

As long as all files are in the same directory, everything is fine:

Now, suppose we want to package this "new" math into a library...There's a convention (an important one) that libraries should be called

`libmymath`

. So, in this case, we can first compile `mymath.c`

into `mymath.o`

(without linking), and then make it into the library. Finally, we do `ran`

on it:It works:

Next, we wish to move our library into a central location---let's make it a subdirectory

`/temp/mylibs`

:Now, we can compile test.c, but we can't link it without giving the linker more info:

We can pass the path directly to let the linker know where to look for our library. This works:

Now the question is whether we can make it shorter?

This works, but is apparently considered bad form. The flags of interest here are I, L, and l.

So for example, we can move the header file to the subdirectory

`/temp/myheaders`

and do:I'm lucky they didn't tell me RTFM! It is actually fairly clearly explained

## 2 comments:

The added printf in

test.cshould read:printf("%3.2f\n", mysqrt(M_PI));

;)

Fixed. Thanks!

Post a Comment