C Programming; a review

Slides:



Advertisements
Similar presentations
Compilation and Debugging 101. Compilation in C/C++ hello.c Preprocessor Compiler stdio.h tmpXQ.i (C code) hello.o (object file)
Advertisements

Overview of programming in C C is a fast, efficient, flexible programming language Paradigm: C is procedural (like Fortran, Pascal), not object oriented.
C Language.
Copyright 2013 – Noah Mendelsohn Compiling C Programs Noah Mendelsohn Tufts University Web:
CSE 303 Lecture 16 Multi-file (larger) programs
Program Development Tools The GNU (GNU’s Not Unix) Toolchain The GNU toolchain has played a vital role in the development of the Linux kernel, BSD, and.
Utilizing the GDB debugger to analyze programs Background and application.
Introduction to C Programming
Binghamton University CS-220 Spring 2015 Binghamton University CS-220 Spring 2015 The CS-220 Development Environment.
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12 Separate Compilation Namespaces Simple Make Files (Ignore all class references.
C Language Brief history In 1972, Dennis Ritchie designed C and it was used on PDP-11 mini- computers In 1974, Unix was rewritten in C C++ and C Advantages.
Unix Continuum of Tools Do something once: use the command line Do something many times: –Use an alias –Use a shell script Do something that is complex.
Guide To UNIX Using Linux Third Edition
Guide To UNIX Using Linux Third Edition
Introduction to Unix (CA263) Introduction to Shell Script Programming By Tariq Ibn Aziz.
CSE 332: C++ program structure and development environment C++ Program Structure (and tools) Today we’ll talk generally about C++ development (plus a few.
1 SEEM3460 Tutorial Unix Introduction. 2 Introduction What is Unix? An operation system (OS), similar to Windows, MacOS X Why learn Unix? Greatest Software.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
1 uClinux course Day 3 of 5 The uclinux toolchain, elf format and ripping a “hello world”
1 Introduction to Tool chains. 2 Tool chain for the Sitara Family (but it is true for other ARM based devices as well) A tool chain is a collection of.
Chapter 2 Software Tools and Assembly Language Syntax.
F13 Forensic tool analysis Dr. John P. Abraham Professor UTPA.
Lesson 7-Creating and Changing Directories. Overview Using directories to create order. Managing files in directories. Using pathnames to manage files.
Introduction to Shell Script Programming
Unix Basics Chapter 4.
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
C++ Basics Structure of a Program. C++ Source Code Plain text file Typical file extension .CPP Must compile the C++ source code without errors before.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Adv. UNIX: large/131 Advanced UNIX v Objectives of these slides: –learn how to write/manage large programs consisting of multiple files, which.
Programming With C.
Introduction to C Programming CE Lecture 7 Compiler options and makefiles.
C Tutorial Session #2 Type conversions More on looping Common errors Control statements Pointers and Arrays C Pre-processor Makefile Debugging.
History of C 1950 – FORTRAN (Formula Translator) 1959 – COBOL (Common Business Oriented Language) 1971 – Pascal Between Ada.
Linux Operations and Administration
1 Programming in C Hello World! Soon I will control the world! Soon I will control the world!
Compilation & Linking Computer Organization I 1 November 2009 © McQuain, Feng & Ribbens The Preprocessor When a C compiler is invoked, the.
Writing a Run Time DLL The application loads the DLL using LoadLibrary() or LoadLibraryEx(). The standard search sequence is used by the operating system.
Chapter 2 part #1 C++ Program Structure
Oct 2001ANSI C Under Unix (v1.0)1 UNIX C Programming under Unix written and presented by M.T.Stanhope.
1 CS503: Operating Systems Spring 2014 Part 0: Program Structure Dongyan Xu Department of Computer Science Purdue University.
Navigating the C++ Development Environment
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Lecture 02 File and File system. Topics Describe the layout of a Linux file system Display and set paths Describe the most important files, including.
Announcements Assignment 1 due Wednesday at 11:59PM Quiz 1 on Thursday 1.
CS252: Systems Programming Ninghui Li Based on Slides by Gustavo Rodriguez-Rivera Topic 2: Program Structure and Using GDB.
CSE 303 Concepts and Tools for Software Development Richard C. Davis UW CSE – 10/11/2006 Lecture 7 – Introduction to C.
LECTURE 3 Translation. PROCESS MEMORY There are four general areas of memory in a process. The text area contains the instructions for the application.
L071 Introduction to C Topics Compilation Using the gcc Compiler The Anatomy of a C Program Reading Sections
Linux Administration Working with the BASH Shell.
Hank Childs, University of Oregon April 13 th, 2016 CIS 330: _ _ _ _ ______ _ _____ / / / /___ (_) __ ____ _____ ____/ / / ____/ _/_/ ____/__ __ / / /
Lecture 3 Translation.
Last week: We talked about: History of C Compiler for C programming
User-Written Functions
Computer Science 210 Computer Organization
Chapter 1: Introduction to computers and C++ Programming
A bit of C programming Lecture 3 Uli Raich.
COSC 350 System Programming
Separate Assembly allows a program to be built from modules rather than a single source file assembler linker source file.
The Linux Operating System
Editor, Compiler, Linker, Debugger, Makefiles
Introduction to C Topics Compilation Using the gcc Compiler
Computer Science 210 Computer Organization
Getting Started: Developing Code with Cloud9
Creating your first C program
Linux Shell Script Programming
Appendix F C Programming Environment on UNIX Systems
Introduction to C Programming
Makefiles, GDB, Valgrind
SPL – PS1 Introduction to C++.
Presentation transcript:

C Programming; a review Ian McCrum www.eej.ulst.ac.uk/~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

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= 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 function Ptr_t->x=3; // same as r.x actually -> is shorthand for (*ptr_r).x

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

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.

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

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

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

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

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/libc.so.N is the shared library and /usr/lib/libc.sa the stub N is actually number, the major version number, currently 6

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)

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

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

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

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

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.

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

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.

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

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

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…