C Programming; a review Ian McCrum ian.

21
C Programming; a review Ian McCrum www.eej.ulst.ac.uk/~ian

Transcript of C Programming; a review Ian McCrum ian.

Page 1: C Programming; a review Ian McCrum ian.

C Programming; a review

Ian McCrum

www.eej.ulst.ac.uk/~ian

Page 2: C Programming; a review Ian McCrum ian.

C uses variables …Every variable has to be “typed”

int I; // We can declare inside or

Float wages=4.50; /* outside of functions */

Note comments!Two methods

We can initialise

We can define our own types… very common in unix

Time_t myruntime; // the special type is defined // in time.h

Page 3: C Programming; a review Ian McCrum ian.

Variables, single or multipleA collection of variables of the same type is an array

A collection of variables of the different types is a struct

Int data[2000]; // refer to first as data[0]

// and the last as data[1999]

Struct rec {int x; char y; float z;}; // get at the bits using the “dot” operatorStruct rec r; // rec is the name of a struct definition (tag)r.x = 3; r.y = ‘a’; r.z= 3.1415; // and r is a struct variable of type rec

We frequently use “pointers” which hold the address of an item

Struct rec *ptr_r; // A pointer that will be used to get at rec structs*ptr_r=&r; // set it to address of r, unusual, more typical to use functionPtr_t->x=3; // same as r.x actually -> is shorthand for (*ptr_r).x

Page 4: C Programming; a review Ian McCrum ian.

Functions, the heart of CThe compiler insists on knowing about these before you use them.We must declare our intentions… the function prototype

What is a function? It does something, it may need data, it may create data. Data is usually a number, the value of a variable.

Beep(); // a function with no parameters and no return value

Void beep(void); // this is how we give the compiler a hint…

Y=sqrt(x); // if x is a integer holding 4 and y is a float or //double, it will end up with a value of 2.0

Double sqrt(double); // compiler will promote int to double

Note the semicolon. It’s a prototype…

Page 5: C Programming; a review Ian McCrum ian.

The first program

#include <stdio.h>

void main(void){

puts“Hello World. \n \t and you ! \n ”); return;}

$Hello World.

and you !

This file holds Constants, variable declarations

and Prototypes

Main is just a function… albeit a special function – it gets executed

first. Here it returns nothing

We do not need to pass data into main (from the shell or from

whoever called main() )

This function is passed one parameter - a

string. It returns nothing

Note the ‘n’ and ‘t’ charactes have a special meaning when prefixed with a slash. This is called “escaping” and is

used in shell programming as well

The shell prints a ‘$’ prompt and then the

output

We return nothing here. It is usual to return a number in Unix. Zero means success and

non-zero means an error occurred.

Page 6: C Programming; a review Ian McCrum ian.

UNIX ProgramsApplications under UNIX are represented by two types of file: executables or scripts. Executables are programs that can be run directly by the computer and correspond to .EXE or .DLL windows programs. Scripts are collections of commands in a text file that are interpreted by another program. Typically the Bourne Shell (sh) or its successor (bash). Other shells include cshell (csh), “Tickle” (tcl), PERL and many others. The text files specify what interpreter is to run them on the first line of text, after a “hash-bang” (#!)

Programs can only run if their location is specified explicitly by the user or through use of the PATH environment variable. This lists directories separated by a colon : (dos uses a semicolon instead!)

The convention for users in linux is that the following are used./bin Here go binaries used for booting the system/usr/bin Here go binaries, standard programs available to users/usr/local/bin Here go binaries available on this computer only

/sbin Here go binaries use for administration, root uses these

Page 7: C Programming; a review Ian McCrum ian.

The C compiler

Used to be called cc, now typically gcc

This “program” actually runs several programs as needed. Preprocessor, compiler, assembler, linker

$man gcc will give help but $info gcc is better

These give a little help on programming in c as well

The compiler must access header files; these are found in /usr/include/<further subdirectories…>

Sometimes the different versions of gcc, libraries or headers can cause problems. You can install many library versions at the same time

Page 8: C Programming; a review Ian McCrum ian.

Include files and other points

$gcc –I /usr/openwin/include fred.c ; echo add extra headers

Grep is your friend, or a modern editor or ide

e.g to find the include file you need to use a EXIT constant

$cd /usr/include ;grep EXIT_ *.h ;echo search all .h’s

stdlib.h:#define EXIT_FAILURE 1 /*use to flag error */

stdlib.h:#define EXIT_SUCCESS 0 /*use to flag ok */

$

Page 9: C Programming; a review Ian McCrum ian.

Library FilesThere are many in UNIX, e.g stdio, dbm or the Maths libraries

Standard system libraries are in /lib and /usr/lib but you can override this with the –L option to gcc. The linker knows this but needs to be told which library, apart from the standard C library, to search… hence you need the .h include files and may need to modify the gcc command line to tell it

Library names all begin with lib then the name proper e.g c

Then follows a ‘.’ and either a or so or sa. For static or shared libraries

$gcc –o fred fred.c /usr/lib/libm.a ;echo explicit reference

$gcc –o fred fred.c -lm ;echo compiler will use .a or .so

Page 10: C Programming; a review Ian McCrum ian.

Static LibrariesA collection of object files kept together, known as archives which is why they end in a .a .You use the ar command to make them and the nm command to list them. ( some systems also need the ranlib program)

Shared LibrariesIf you compiled, statically linked and ran 5 c programs that each used printf for instance, then there would be 5 copies of printf.o in memory at the one time…shared libraries get around this inefficiency. Each program gets a stub and this will load or access a single copy of printf which gets loaded at runtime by the first program needing it.

/usr/lib/libc.so.N is the shared library and /usr/lib/libc.sa the stub

N is actually number, the major version number, currently 6

Page 11: C Programming; a review Ian McCrum ian.

Shared Libraries

The major version number should match what the author used, upwards compatiblity is not guaranteed. Minor version number differences are ok and downloaded source code should compile ok.

The actual libraries are something like/usr/lib/libc.so.5.2.8 but a “link” is made to libc.so.5

Think of a link as a shortcut, a bit like a “text substituion”. We’ll look at the three types of link when we look at the UNIX file system, (inodes etc)

Page 12: C Programming; a review Ian McCrum ian.

More on Shared Libraries(I am spending time on these because it is where compilation of downloaded programs may fail.)

In linux the program ld.so (actually ld-linux.so) actually loads and resolves any function calls that require loading or finding in memory. ld.so will search /etc/ld.so.conf for a list of libraries

To add shared libraries here you run ldconfig (c.f man page)

To see what shared libraries are needed in a program use ldd$ ldd program ;echo this may list dozens of libraries

libc.so.5 (DLL Jump 5.2p18 ) => /lib/libc.so.5.2.8Windows uses .DLL files for a similar purpose“Dynamic Link Libraries” is quite a good name for thisHowever shared libraries are all loaded or found at program start time. It is also possible to load and unload dynamically

Page 13: C Programming; a review Ian McCrum ian.

Compiling C$mkdir c;cd c;mkdir test1;cd test1;vi test1.c;ls -l

$gcc test1.c;echo This produces a file called a.out

$./a.out;echo this will run a.out (if its file permissions are x)

Your own directories are not on the PATH (type $echo $PATH)

$gcc test1.c –o test1 ; echo produces a binary called test1

$gcc test1.c –g –o test1 ; echo test1 binary with debug code

$gdb test1;echo run debugger, try list, breakpoint and step...

Page 14: C Programming; a review Ian McCrum ian.

The debugger gdb

Has good help built in, is very powerful, e.g you can run a program on one PC and the debugger on another, access by adding a tiny stub of code to the target and linking the two machines by a serial lead or ethernet link.

“A debugger is a crutch for a bad programmer” says Ian McCrum

You compile using the –g option and then run $gdb test1(gdb)list ;note the prompt, you are now running gdb(gdb)break 6 ;note give a line number or function name here(gdb)run ;stops at breakpoint(gdb)print I ;you can print arrays, structs, pointers or look at the calling stack(gdb)next ;single steps, and lists next line to be executed, use continue to run

Or use p,l,b,r,n,c

Page 15: C Programming; a review Ian McCrum ian.

Other Programming Tools

There are version control tools for multi programmer projects: CVS or “Concurrent Version Control”

There are Profiler tools for recording where time is spent

There are “packaging” tools to ease installing programs.Varies according to which distribution you use but includes: autoconf to manage installation from sourceAnd rpm to allow installation from binary, including man pages and documentation

There are memory leak and buffer overflow detectors

(xref) cross reference tools, style analysers (lint) etc,.

There are tools to ease single programmer development of multiple file projects (make) or write your own script

Page 16: C Programming; a review Ian McCrum ian.

The make programIf in a directory full of C files there is a text file with the default name of makefile then running $make will cause it to be used by the make program

A makefile lists all the unix commands necessary to build a complete program. As a series of steps. E.g if part1.c and part2.c and main.c are in a program, then make will cause the compiler to create part1.o, part2.o and main.o Then the linker will be called to create main, the final executable

The power of make is that it examines timestamps. If a change is made to part2.c and make run again, only part2.c is compiled. The linker links the old part1.o, old main.o and the new part2.o to make the final program.

Page 17: C Programming; a review Ian McCrum ian.

Makefiles• When programming large applications

– Better to modularise.– Keep individual source files small.– Instead of one large file.

• Difficult to edit.

• Slow to compile.

– Not easy to do manually.– Use a “makefile.”

Page 18: C Programming; a review Ian McCrum ian.

Makefile example

• Consider, program contained in two separate source files.– “main.c”– “sum.c”– Both contain header “sum.h”

• Require executable file to be named “sum”• Next slide shows a simple makefile that

could be used.

Page 19: C Programming; a review Ian McCrum ian.

Makefile example

# Make file for sum executablesum: main.o sum.o

gcc –o sum main.o sum.omain.o: main.c sum.h

gcc –c main.csum.o: sum.c sum.h

gcc –c sum.c

Comment line preceded with “#”

“Dependency line”

“Action line”

Dependency line must start in column 1

Action line must begin with a tab character

Dependency line + Actionline = “Rule”

Page 20: C Programming; a review Ian McCrum ian.

Makefile example

# Make file for sum executablesum: main.o sum.o

cc –o sum main.o sum.omain.o: main.c sum.h

cc –c main.csum.o: sum.c sum.h

cc –c sum.c

Page 21: C Programming; a review Ian McCrum ian.

Summary• C Programming; variables and functions• Libraries and include files (static & shared)• Compiling• Debugging• Make and others

Yet to do autoconf and rpm, compiling the kernel

Now continue learning vi and running commands…