1

Possible Duplicate:
Why do you have to link the math library in C?

I am learning C using the GCC compiler (on Linux).

I recently moved from using Code::Blocks to using Geany, and I have noticed that Geany doesn't automatically link to any required libraries. For example, when I would use #include <math.h> in Code::Blocks, it would pick up on that and automatically link in the corresponding math library when I compile. However, Geany doesn't do that and I must manually add in build commands, such as -lm for the math library, to get the compilation to work.

However, I noticed that including the string.h header, and using functions from it, compiled fine without linking in the string library. Why is that? Is it that the string.h header defines all the functions itself? Could someone please explain why some libraries seem to need to be linked whereas others do not.

On a similar note, has anyone had experience in telling Geany to automatically link in the required libraries? That would make the compiling a lot easier.

Community
  • 1
  • 1
james
  • 477
  • 2
  • 5
  • 10

2 Answers2

2

All libraries need to be linked in. However, the library functions in the string.h header are part of the C library that is linked by default into all C programs unless you request otherwise. By contrast, the math library functions are not linked by default because many C programs don't need them and linkers weren't always optimized.

On ancient systems, if math functions were contained in libc, then compiling all programs would be slower, the output executables would be larger, and runtime would require more memory, with no benefit to most programs which do not use these math functions at all. These days we have good support for shared libraries, and even when statically linking, the standard libraries are set up so that unused code can be discarded, so none of these are good reasons anymore.
    -- Why do you have to link the math library in C

Community
  • 1
  • 1
David Schwartz
  • 179,497
  • 17
  • 214
  • 278
1

On most systems, only the functions of the maths library are separated into libm.so or libm.a (because it's huge). The functions declared in the other header files are present in libc.so or libc.a, which is always automatically linked by GCC (not the IDE!).

There are some exceptions, however, as the C standard doesn't define how libraries should be organized. On some linux systems, the time_* functions are pulled out into a separate library, librt.so (or .a). Whilst on Mac OS X, all the C standard library is put into libSystem.dylib along with CommonCrypto and some BSD APIs (e. g. libkern).