[prog] using a -ln option with GCC when compiling c code with math.h

Meredydd meredydd at everybuddy.com
Tue Jun 24 09:31:15 EST 2003


The answer to this one is about the structure of the C language itself, and I 
probably won't do full justice to it, but here's a quick summary:

C itself has been described as "a very portable way to write assembly code". 
While not strictly accurate, it gives you a feeling for how the language 
works - there are few abstractions between you and the hardware. However, 
this isn't ideal if you want to create high-level applications with it. As a 
result, functions are created - functions such as printf(), strcpy() and the 
rest. They are *not* part of the C language per se - they are functions 
written *in* C, so you don't have to implement them each time you write an 
application. These functions live in the "standard C library" - also known as 
libc. This is why things can go horribly horribly wrong when you upgrade libc 
- if you get yourself wedged in a situation where libc doesn't work, you can 
be pretty stuffed, because even the basic programs such as "cp", "mv" and the 
more complicated ones like "rpm" or "dpkg" are usually dynamically linked - 
that is to say, they rely on being able to load libc at run-time to use those 
vital functions.

In any case, at some point a Decision Was Taken, that mathematical functions 
such as cos, sin - in fact, anything that uses math.h - are not vital enough 
to live in the standard C library. Instead, they have their own library, 
usually in /usr/lib/libm.a, where they are stored.

A library (well, the .a variety anyway) is in fact just an archive file 
(created using the "ar" archiver), containing a lot of .o files. When you 
pass gcc something like:

gcc -o myprog proggie.c -lm

...gcc will look in all the library directories (/lib, /usr/lib, 
/usr/local/lib, etc) for a file called "libm.a", and link all the .o files in 
that archive as well to create the final executable.

Borland just hides this entire process from you, which is why you haven't 
encountered it yet. By the way, why did you say "-ln" there - surely you mean 
"-lm"? On my system, there is no such file as "libn.a", which is what gcc 
would look for if you were to specify that option on the command line.

Meredydd

On Monday 23 June 2003 08:25, Guru - wrote:
> Hi.
> I'm just wondering (this problem caused me a lot of trouble during Uni
> until I figured it out),
> why is it necessary to use the -ln flag with GCC when compiling something
> that uses math.h?
> (this problem forced me to go back to Borland C until I figured it out).
>
> Thanks



More information about the Programming mailing list