You are on page 1of 32

Unix Systems Programming

(CSE 3041)

Programming in the Large


Chapter-12

SOA
Deemded to be University

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 1 / 32
Personal Libraries

Availability of C’s standard libraries:


I Simplifies program development.
I Standard libraries(SL) are not extensive enough to handle every need
A function that would be useful in different contexts requires:
I Copying the code of functions into other programs to allow reuse
I Cumbersome, especially compared to the way we get access to SL.
In fact, use #include to make available personal libraries as well. C
permits
I Source code files to be compiled separately and then linked prior to
loading and execution,
I We can provide our personal libraries as object files;
I Programs using our personal libraries need not first compile the functions
in them.

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 2 / 32
(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 3 / 32
Header Files

To create a personal library, make a header file


I a text file containing all the information (interface information) about a
library needed
F by the compiler to translate a program that uses the facilities defined in
the library and
F by a person to understand and use the library.
Typical contents of a header file include:
I a block comment summarizing the library’s purpose
I #define directives naming constant macros
I type definitions
I function declarations (prototypes)
I block comments stating the purpose of each library function and decla-
rations of the form
keyword extern in a function declaration notifies the compiler that the
function’s definition will be provided to the linker.

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 4 / 32
Implementation files

The header file describes what the functions of the library do;
The implementation file shows how a function does it.
A library’s implementation file is a .c file
I the code of all the library functions and
I any other information needed for compilation of these functions.
Elements of an implementation file
I a block comment summarizing the library’s purpose
I #include directives for this library’s header file and for other libraries
used by the functions in this library
I #define directives naming constant macros used only inside this library
I type definitions used only inside this library
I function definitions including the usual comments

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 5 / 32
Using a Personal Library

To use a personal library, one must complete these steps:


Creation
C1 Create a header file containing the interface information for a program
needing the library.
C2 Create an implementation file containing the code of the library func-
tions and other details of the implementation that are hidden from the
user program.
C3 Compile the implementation file. This step must be repeated any time
either the header file or the implementation file is revised.
Use
U1 Include the library’s header file in the user program through an #include
directive.
U2 After compiling the user program, include both its object file and the
object file created in C3 in the command that activates the linker

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 6 / 32
Compile and use
$ gcc -c planet equal.c -o planet equal.out
$ gcc -c scan planet.c -o scan planet.out
$ gcc -c print planet.c -o print planet.out
$ gcc -o main all.out planet main.c planet equal.out
scan planet.out print planet.out

Static library
$ gcc -c planet equal.c -o planet equal.out
$ gcc -c scan planet.c -o scan planet.out
$ gcc -c print planet.c -o print planet.out
$ ar r libPO.a planet equal.out scan planet.out print planet.out
$ gcc -o planet with lib.out planet main.c -L./ -lPO

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 7 / 32
Pointer notations
Consider the declaration:
int i = 3 ;

This declaration tells the C compiler to:


a. Reserve space in memory to hold the integer value.
b. Associate the name i with this memory location.
c. Store the value 3 at this location.

Figure: variable i location in memory.

Important: i’s address in memory is a number.


(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 8 / 32
(a) Where the variable would be stored ?
In memory or CPU register ?
(b) What will be the initial value of the variable?
If initial value is not specifically assigned.(i.e. the default initial value).
(c) What is the scope of the variable ?
In which functions the value of the variable would be available.
(d) What is the life of the variable ?
How long would the variable exist.

Storage classes
To fully define a variable one needs to mention not only its
‘type’ but also its ‘storage class’.
Why now ? variables have certain default storage classes.
Default: the compiler will assume a storage class depending on
the context in which the variable is used.

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 9 / 32
Storage classes

(a) Automatic storage class


(b) Register storage class
(c) Static storage class
(d) External storage class

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 10 / 32
Identifier

An identifier can denote an object; a function; a tag or member of a struc-


ture, union, or enumeration; a typedef name; a label name; a macro name;
or a macro parameter.
Identifiers and Scope
An identifier can be used only in a region of program text called its scope.
The scope begins at the identifier declaration.
If two different entities are designated by the same identifier, their scopes must be disjoint, or one scope
must be completely contained in the other.
In the inner scope, the other entity is hidden and cannot be referenced by that identifier.
If the declaration occurs inside a block, the identifier has block scope and the scope ends at the end of the
block.
If the declaration occurs outside any block, the identifier has file scope, and the scope ends at the end of
the file in which it is declared.

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 11 / 32
Linkage class

Identifiers declared more than once may refer to the same object be-
cause of linkage.
Each identifier has a linkage class of external, internal or none.
External: Declarations in a program of a particular identifier with ex-
ternal linkage refer to the same entity.
Internal: Declarations in a file of a particular identifier with internal
linkage represent the same entity.
No linkage: Each declaration of an identifier with no linkage represents
a unique entity.

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 12 / 32
Automatic storage class

Automatic storage class

Formal parameters and local variables of functions are variables that


belong to this storage class.
The keyword auto is used for this storage class.
An identifier of an object declared inside a block has no linkage. Each
identifier denotes a unique object.

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 13 / 32
Register storage class

Register storage class

A value stored in a CPU register can always be accessed faster than


the one that is stored in memory.
Candidate variable: used at many places in a program.
Can we say for sure that the value of register variable would be stored
in a CPU register?
If the microprocessor has 16-bit registers then can it hold a float or a
double value ?

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 14 / 32
Static storage class
Static storage class

When declared inside a function, scope is local to the function. Life-


time: As above.
An identifier of an object declared outside any block has static storage
class.
Such objects with static storage class have a lifetime that is the duration
of the program.
They are initialized once and retain their last stored value.
In the absence of no explicit initialization, they are initialized to 0.
(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 15 / 32
Static variables

Figure: Program 2
Figure: Program 1

Static variables that are not explicitly initialized in their declarations


are initialized to 0 at runtime.
Typically, the initialized static variables are part of the executable mod-
ule on disk, but the uninitialized static variables are not.

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 16 / 32
Use of Static Variables

A static variable can hold internal state information between calls to a


function.
Problem statement
Write a function that sorts an array of integers and counts the number of
interchanges made in the process. Use bubble sort algorithm.
Define main function in a separate file named BSmain.c .

Define two functions with name bubbleSort and onePass in another file named bubbleSort.c .

main in BSmain.c should call bubbleSort function to sort the elements in the input array.

Function bubbleSort should call the function onePass to perform one pass over the unsorted input.

Compile the auxilary file bubbleSort.c .

Now, compile BSmain.c and link it to bubbleSort.out .

Ensure that onePass cannot be called directly from the main in BSmain.c .

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 17 / 32
Static storage class

A poor programming practice :


Using a static local variable to retain data from one call to a function
to the next.
Function transformation depends on input arguments as well as static
variable.
Increase program complexity (reader’s perspective).

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 18 / 32
Using static: strtok() library function in C

#include <string.h>
char *strtok(char *str, const char *delim);

strtok splits a string into tokens.


First call to strtok: the string to be parsed should be specified in str.
In each subsequent call that should parse the same string, str must be
NULL . (i.e. the first call to strtok is different from subsequent calls)
The second argument to strtok is a string of allowed token delimiters.
Each successive call to strtok returns the start of the next token and
inserts a ’\0’ at the end of the token being returned . The strtok
function returns NULL when it reaches the end of the string, str.
strtok does not allocate new space for the tokens, but rather it tokenizes str
in place .
To access the original str after calling strtok, its a must to save a copy of the
string.
(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 19 / 32
Programming problems

Given
CSE:ITER:SOADU:::::BBS:OR:IND::ASIA::::::EARTH

P1 Write a program to generate tokens present in the above string. A


token is a sequence of characters containing no specified delimiter.
Print one token per line on the terminal. Use strtok C library function.
P2 Write codes to verify the in-place tokenization operation/behavior of
strtok() function.
P3 Modify the program to print the count of the number of tokens.
P4 Code Xstrtok() function. Working of your Xstrtok() function should
imitate the build-in strtok() function in every aspect.

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 20 / 32
Library Function: strspn()

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 21 / 32
Example: strspn()

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 22 / 32
(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 23 / 32
Immature use of static variables in strtok implementation

To perform an in-place string tokenization, strtok must use an in-


ternal static variable to keep track of the current location of the next
token to parse within the string.
However, when calls to strtok with different parse strings occur in the
same program, the parsing of the respective strings may interfere be-
cause there is only one variable for the location.

Thread-unsafe behavior
The behavior that causes the above code to fail also prevents strtok from being
used safely in programs with multiple threads.
If one thread is in the process of using strtok and a second thread calls strtok ,
subsequent calls may not behave properly.
A thread-safe function called strtok r should be used in place of strtok. The
r stands for reentrant, indicating the function can be reentered (called again)
before a previous call finishes.

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 24 / 32
C Library Function strtok r()

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 25 / 32
Using strtok r in place of strtok

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 26 / 32
A practical example: The wc utility in UNIX

Programming problem
Write a program to determine the average number of words per
line in a command-line argument.

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 27 / 32
Static: AFFECTS STORAGE OR LINKAGE DEPENDING
ON THE CONTEXT.

The static qualifier can affect either the storage class or linkage class of
an object depending on the context.
An identifier representing a function has external linkage by default.
This means that it can be referenced in any file of the program.
When static is applied to a function, it always changes its linkage
class from the default of external to internal.
Functions do not have a storage duration.
For variables declared inside a block, the linkage class is always none
and static changes the storage class from automatic to static.
For variable declared outside any block, the storage class is always static
and the static specifier changes the linkage class from external to
internal.

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 28 / 32
External storage class

External storage class

Notifies the compiler that such a function/variable exists and that the
linker will know where to find it.
To reference a top-level variable in the region of its source file that
precedes its declaration or in another source file.
The names of the functions themselves are of storage class extern ,
meaning that they will be available to the linker.

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 29 / 32
External storage class

A declaration beginning with the keyword extern allocates no memory; it


simply provides information for the compiler.

(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 30 / 32
(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 31 / 32
(Ashish Kumar Gupta, Ph.D.) Chapter-12, PIL, C programming December 24, 2021 32 / 32

You might also like