Reputation: 29497
I am brand new to C programming (but not programming) and am trying to understand how libraries and header files work together, particularly with respect to packaging and distribution.
After reading this excellent question and its answer, I understand that the header file(s) act as the API to a library, exposing capabilities to the outside world; and that the library itself is the implementation of those capabilities.
However one thing that I cannot seem to find a good explanation of is: how are header files packaged into or distributed with the libraries?
When I do a #include "mylib.h"
, how does the linker know where to find:
mylib.h
mylib.h
.Upvotes: 2
Views: 659
Reputation: 134326
how does the linker know where to find: (1) the header file itself,
mylib.h
#include <mylib.h>
, it searches the header file in the system defined include PATH.#include "mylib.h"
, it searches the header file in the system defined include PATH and in the current directory.if the header file is present in some other hierarchy, you can provide the path to get the header file with -I
option with gcc
.
(2) the library implementing mylib.h?
You need to provide the path to the library using -L
(in case of non-standard path to the library) and link the library using -l
option.
As per the convention, if the (shared) library is named libmylib.so
, you can use -lmylib
to link to that directory.
For example , consider the pow()
function.
It is prototyped in math.h
, so in your source file, you need to add #include <math.h>
to get the function declaration.
Then, at compile (rather, linking) time, you need to link it with the "math" library using -lm
to get the function definition.
Upvotes: 3