Presentation is loading. Please wait.

Presentation is loading. Please wait.

C Programming; a review

Similar presentations

Presentation on theme: "C Programming; a review"— Presentation transcript:

1 C Programming; a review
Ian McCrum

2 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

3 Variables, single or multiple
A collection of variables of the same type is an array Int data[2000]; // refer to first as data[0] // and the last as data[1999] A collection of variables of the different types is a struct Struct rec {int x; char y; float z;}; // get at the bits using the “dot” operator Struct rec r; // rec is the name of a struct definition (tag) r.x = 3; r.y = ‘a’; r.z= ; // 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 function Ptr_t->x=3; // same as r.x actually -> is shorthand for (*ptr_r).x

4 Functions, the heart of C
The compiler insists on knowing about these before you use them. We must declare our intentions… the function prototype Void beep(void); // this is how we give the compiler a hint… Double sqrt(double); // compiler will promote int to double Note the semicolon. It’s a 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 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

5 The first program $Hello World. and you ! #include <stdio.h>
Main is just a function… albeit a special function – it gets executed first. Here it returns nothing This file holds Constants, variable declarations and Prototypes #include <stdio.h> void main(void){ puts“Hello World. \n \t and you ! \n ”); return; } $Hello World. and you ! 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.

6 UNIX Programs Applications 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

7 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

8 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 */ $

9 Library Files There 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

10 Static Libraries Shared Libraries
A 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 Libraries If 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/ is the shared library and /usr/lib/ the stub N is actually number, the major version number, currently 6

11 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/ but a “link” is made to 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)

12 More on Shared Libraries
(I am spending time on these because it is where compilation of downloaded programs may fail.) In linux the program (actually actually loads and resolves any function calls that require loading or finding in memory. will search /etc/ 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 (DLL Jump 5.2p18 ) => /lib/ Windows uses .DLL files for a similar purpose “Dynamic Link Libraries” is quite a good name for this However shared libraries are all loaded or found at program start time. It is also possible to load and unload dynamically

13 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...

14 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 Or use p,l,b,r,n,c 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

15 Other Programming Tools
There are tools to ease single programmer development of multiple file projects (make) or write your own script 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 memory leak and buffer overflow detectors (xref) cross reference tools, style analysers (lint) etc,. There are “packaging” tools to ease installing programs. Varies according to which distribution you use but includes: autoconf to manage installation from source And rpm to allow installation from binary, including man pages and documentation

16 The make program If 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.

17 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.”

18 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.

19 Makefile example Comment line preceded with “#”
# Make file for sum executable sum: main.o sum.o gcc –o sum main.o sum.o main.o: main.c sum.h gcc –c main.c sum.o: sum.c sum.h gcc –c sum.c “Dependency line” “Action line” Dependency line + Action line = “Rule” Dependency line must start in column 1 Action line must begin with a tab character

20 Makefile example # Make file for sum executable sum: main.o sum.o
cc –o sum main.o sum.o main.o: main.c sum.h cc –c main.c sum.o: sum.c sum.h cc –c sum.c

21 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…

Download ppt "C Programming; a review"

Similar presentations

Ads by Google