PART 1: LIBRARIES
- The Standard C Library provides a huge wealth of built-in functions and functionality that is available to you to include in your programs. All this functionality becomes available when you #include
the appropriate header files.
- Functions in a C library can be used and accessed by programmers to create several different programs.
- As a programmer, you may find yourself using the same function or functions repeatedly. In this case, it is best to put this function or functions in a library to speed up the compilation of the program.
- A library in C is a collection of header files, exposed for use by other programs. The library therefore consists of an interface expressed in a .h file (named the "header") and an implementation expressed in a .c file.
- This .c file might be precompiled or otherwise inaccessible, or it might be available to the programmer.
(Note: Libraries may call functions in other libraries such as the Standard C or math libraries to do various tasks.)
C libraries store files in object code. When a C program is compiled, the compiler generates object code.
After generating the object code, the compiler also invokes linker. One of the main tasks for linker is to make code of library functions (e.g. printf(), scanf(), sqrt(), ..etc) available to your program.
A linker can accomplish this task in two ways, by copying the code of library function to your object code, or by making some arrangements so that the complete code of library functions is not copied, but made available at run-time.
There are two types of libraries in C Language:
i) Static Libraries: Static Linking and Static Libraries is the result of the linker making copy of all used library functions to the executable file.
ii) Dynamic Libraries: Dynamic Linking doesn’t require the code to be copied, it is done by just placing name of the library in the binary file. The actual linking happens when the program is run, when both the binary file and the library are in memory.
Let’s discuss more about these libraries,
- Static Linking creates larger binary files, and need more space on disk and main memory. Examples of static libraries (libraries which are statically linked) are, .a files in Linux and .lib files in Windows.
- Static libraries are a collection of object files that are joined to a source code before it is compiled by a static linker, making it completely self-sufficient. They produce object files and standalone executable files.
- These libraries can be linked to a program without recompiling the code.
- Static linking creates larger files because of the creation of the standalone (exe. file) files.
- Static libraries are added during the linker phase of the compilation process.
- During the linker phase: the linker links access all the libraries to link functions to the program.
- Static libraries are merged with other static libraries to create an executable program.
- During the compilation of a program, the static library is called to execute the program.
- To create a static library you have to use the ‘ar’ or archiver program. The idea is that these functions are being archived until needed. A function saved in .c format is recompiled into an object file, “.o”.
Following are some important points about static libraries.
- For a static library, the actual code is extracted from the library by the linker and used to build the final executable at the point you compile/build your application.
- Each process gets its own copy of the code and data. While in case of dynamic libraries it is only code shared, data is specific to each process.
- For static libraries memory footprints are larger. For example, if all the window system tools were statically linked, several tens of megabytes of RAM would be wasted for a typical user, and the user would be slowed down by a lot of paging.
- Since library code is connected at compile time, the final executable has no dependencies on the library at run time i.e. no additional run-time loading costs, it means that you don’t need to carry along a copy of the library that is being used and you have everything under your control and there is no dependency.
- In static libraries, once everything is bundled into your application, you don’t have to worry that the client will have the right library (and version) available on their system.
- One drawback of static libraries is, for any change(up-gradation) in the static libraries, you have to recompile the main program every time.
- One major advantage of static libraries being preferred even now “is speed”. There will be no dynamic querying of symbols in static libraries. Many production line software use static libraries even today.
- Dynamic Linking doesn’t require the code to be copied, it is done by just placing name of the library in the binary file.
- The actual linking happens when the program is run, when both the binary file and the library are in memory. Examples of Dynamic libraries (libraries which are linked at run-time) are, .so in Linux and .dll in Windows.
- Since static linking directly inserts machine code into the executable, C programs involving many functions can result in large, unwieldy executables.
- For this same reason, static linking is not flexible when it comes to editing libraries after-the-fact. With static linking, any changes made to a library after compilation will not register in existing executables — recompilation is required.
- Dynamic libraries, beautifully, solves above issues of static libraries. Both static and dynamic libraries are functionally equivalent. However, when using static libraries, machine code is inserted directly into executable(.exe). With dynamic libraries, machine code is only loaded and executed at runtime.
Following are some important points about Dynamic libraries.
- Dynamic libraries are a collection of object files which are referenced at build time to give the executable information how they will eventually be used, but they aren’t used until run time. In other words, these objects are dynamically linked into executables that use them.
- Dynamic libraries are shared libraries with specific functions launched during the execution of a program and contribute to “reduced memory consumption”.
- Dynamic linking is a two-step process that relies on accessing the addresses of code.?
- The first step occurs at compilation. When a file is compiled with a dynamic library, instead of copying the actual object code contained in the library, the linker simply scans the code contained and checks for missing symbols.
- The second step, which occurs at runtime, the magic happens — a dynamic loader officially links the object code contained in the library to the running process.
- Through this process, dynamic libraries eliminate the drawbacks of its static counterpart. Since object code is not directly inserted, executables maintain a compact size no matter the number of linked functions. Correspondingly, since dynamic linking only relies on addresses of code, edits can be made to the library without worry — the code contained will only be referenced, linked, and executed at runtime.
- Nothing is perfect, though. For each of these advantages over static libraries, dynamic libraries do feature one disadvantage — they are slower. The process of dynamically loading and linking code at runtime takes more time than it does in static linking. When deciding to use either a static or dynamic library, decide whether you prioritize efficiency (static) over flexibility (dynamic).
PART 2: HEADER FILES
- Header files contain a bunch of files that help the user to include the predefined functions according to his requirements.
- You can add header files using the preprocessor directive #include
.
- C provides a series of predefined functions embedded in the header files in the C library.
- We use these functions to perform a specific task with the help of a header file.
- Library functions are also declared in the header files and you must have to include header file in the program.
- For example, if you are using sqrt() function to find the square root of any number, you will have to include math.h header file.
In standard C Library there are 19 header files in the Standard C Library. All files have the .h file extension.
??????Examples:??????#include
<stdio.h>
?????????????????????????????#include
<string.h>
Note: In standard C++ Library there are a total of 49 header files in the Standard C++ Library. This includes equivalents of the 19 Standard C Library header files. All of the equivalent C header files have a ‘c’ prepended to the name and have no .h file extension.
?????????Examples: ??????#include
<cstdio>
????????????????????????????????#include
<cstring>
Standard C++ library Includes 30 additional header files (49 totals).
Categories of Header files in C:
?1)??Diagnostic - Provides diagnostic and debugging functionality and exception (run time error) handling. (<assert>, <errno>, <stdexcept>)
2)??Input /Output - All the headers providing input and output functionality, both standard C I/O and C++ stream I/O. (<stdio>, <conio>,<stdio>, <stdlib>, <wchar>, <fstream>, <iomanip>, <ios>, <iosfwd>, <iostream>, <ostream>, <strstream>, <streambuf>)
3)??Language Support - Provides functionality for support of the C language. Advanced stuff with a lot of OS functionality. (<float>, <limits>, <setjmp>, <signal>, <stdarg>, <stddef>, <stdlib>, <time>, <exception>, <limits>)
4)??Localization - Provides support for different cultural settings, i.e. other language supports. Chinese, Japanese, Korean, Russian, and Arabic languages for example (<locale>)
5)??Numeric - Provides support for working with complex mathematical and numeric-related equations. (<math>, <complex>, <stdlib>, <numeric>, <valarray>)
6)??String - Support for strings and characters (<ctype>, <stdlib>, <string>, <wchar>, <wctype>, <string>)
7)??General Utility - Miscellaneous useful functions for things like time and date, memory management, etc. (<time>, <functional>, <memory>, <utility>
8)??Algorithm (STL) - An assortment of algorithm implementations that are part of the Standard Template Library. (<algorithms>, <stdlib>,)
9)??Container (STL) - Provides an assortment of containers for the Standard Template Library. Many of the containers are variations on the Abstract Data Types of this class. (<deque>, <list>, <map>, <queue>, <set>, <stack>, <vector>)
10)????Iterator (STL) - Functions used to iterate through the elements of a container. (<iterator>)
Some commonly used header file in c are as follow:
<stdio.h>???: Standard input output?????????- Input/Output functions
<conio.h>??: Console input output???????????- Console Input/Output functions
<stdlib.h>??: Standard library??????????????????- General utility functions
<math.h>??: Mathematics functions
<string.h>?: String functions
<ctype.h>??: Character handling functions
<time.h>???: Date and time functions
<float.h>???: Limits of float types
<limits.h>??: Size of basic types
<wctype.h>: Functions to determine the type contained in wide character data.
Let’s see contains (Includes but not limited to) of some header files:
<ctype.h> :Functions to test characters. Argument must be an integer whose value is an unsigned char (ASCII 0-128) or EOF (-1). Functions return true if the character argument meets the conditions.
- isalnum(c) alphanumeric character (letter or digit)
- isalpha(c) letter
- iscntrl(c) control character (ASCII 0-31)
- isdigit(c) decimal digit
- islower(c) lower case letter
- ispunct(c) printing character except for space or letter or digit, i.e. is punctuation
- isspace(c) space, form feed, newline, CR, tab, vertical tab, i.e. white space.
- isupper(c) upper case letter
- isxdigit(c) hexadecimal digit
Also includes two handy functions:
- int tolower(int c) converts c to lower case if a letter
- int toupper(int c) converts c to upper case if a letter
<string.h> : Provides many "string" handling functions. Arguments are character arrays, or occasionally integers designating a length and/or location.
- char *strcpy(s,ct) Copy string ct to string s, including the '\0'; return s
- char *strncpy(s,ct,n) Copy at most n characters of ct to s; return s
- char *strcat(s,ct) Concatenate string ct to end of string s; return s.
- char *strncat(s,ct,n) Concatenate at most n characters of ct to end of s; return s
- int strcmp(cs,ct) Compare string cs to string ct; return <0 if cs<ct, 0 if cs==ct, or >0 if cs>ct
- int strncmp(s,ct,n) Compare at most n characters of string cs to string ct; return <0 if cs<ct, 0 if cs==ct, or >0 if cs>ct
- char *strchr(cs,c) Return pointer to first occurrence of c in cs or NULL if not present.
- char *strrchr(cs,c) Return pointer to last occurrence of c in cs or NULL if not present.
- char *strstr(cs,ct) Return pointer to first occurrence of string ct in cs, or NULL if not present
- size_t strlen(cs) Returns length of cs (treat as integer return value)
- char *strtok(s,ct) Returns a token split from s using delimiters in ct. In other words this is a parser.
Example: If ct=" \t\n", each call to strtok will split off a token from string s delimited by a space, tab, or newline.
<math.h> : Provides a variety of math functions. Functions include but are not limited to...
- sin(x) Returns sine of x
- cos(x) Returns cosine of x
- tan(x) Returns tangent of x
- asin(x) Returns arcsine of x in range [-π/2,π/2], x contained in [-1,1]
- acos(x) Returns arccosine of x in range [0,π], x contained in[-1,1]
- atan(x) Returns arctangent of x in range [-π/2,π/2]
- sinh(x) Returns hyperbolic sine of x
- cosh(x) Returns hyperbolic cosine of x
- tanh(x) Returns hyperbolic tangent of x
- exp(x) Returns function, ex
- log(x) Returns natural logarithm, ln(x), x>0
- log10(x) Returns base 10 logarithm, log10(x), x>0
- pow(x,y) Returns xy, a domain error occurs if x=0 and y<=0,or if x<0 and y is not an integer.
- sqrt(x) Returns sqrt of x, x>=0
- ceil(x) Returns smallest integer not less than x
- floor(x) Returns largest integer not greater than x
<stdlib.h> : The standard library includes a variety of useful functions including but not limited to...
- double atof(const char *s) Converts string to float
- int atoi(const char *s) Converts string to int
- long atol(const char *s) Converts string to long
- int rand(void) Returns pseudo-random number in range 0 to RAND_MAX which is usually 32767
- void srand(unsigned int seed) Seeds random number generator with seed.
- These next 4 can be used to dynamically allocate variables, arrays, etc. in C.
- void *calloc(size_t nobj, size_t size) Returns pointer to space for an array of nobj objects of size size or NULL if not enough memory. Space is initialized to zeros.
- void *malloc(size_t size) Returns pointer to space for an object of size size or NULL if not enough memory. Space is uninitialized.
- void *realloc(void *p, size_t, size) Reallocates the size of memory allocated to object pointed to by p
- void free(void *p) Free the memory occupied by the object pointed to by p
- These have largely been replaced by the use of the new function in C++:
- void exit(int status) Causes an immediate normal program termination returning to the caller (usually the operating system) an integer status which can signal the exit status, i.e. What has occurred.
- void system(const char *s) Used on UNIX and PC systems. Causes string s to be passed to the operating system to be executed as if it was typed on a command line.
- int abs(int n) Returns absolute value of its integer argument. (don't know why this one is here and not in math.h)
List of articles from the series:
CH 3) Libraries & Header files
References:?Wikipedia, CMan(Bell Labs), GeeksforGeeks, guru99 and various other blogs, videos and sites on available internet.
If you find any errors or disinformation in this article, then please inform me.