A Practical Guide to Computer Programming By Bjørn S. Nilsen

Preview:

Citation preview

A Practical Guide toComputer Programming

By

Bjørn S. Nilsen

Topics to cover• What Problem are you trying to solve.• How to write and compile a program, simplified.• Basics of the C and C++ language.• Details about compiling a program and the like.• Libraries, using existing.• ROOT as library and C++ interpreter• Writing Libraries and an introduction to AliRoot.• An introduction to Distributed (Grid) computing.• The ALICE Virtual Monte Carlo, Data

Reconstruction and Analysis framework.• AliEn, CAF, and ALICE Data Analysis.

What Problem are you trying to Solve?

• Compute Language– What have others used– What are you familiar with

• Operating systems– Linux (hundreds of flavors), MS Windows, IBM OS2, Mac

OSX, Unix (BCS/ATT, Solaris, …), VMS, … – DOS, QNX, RTLinux, VxWorks, Windows CE

• Selecting your “Computer”– Real-time systems– Interactive systems– Batch Systems

Computer Languages

• FORTRAN, COBAL, C, …• Pascal, Basic, …• C++, Java, …• Tex/LaTex, HTML, XML, Exel, …• Perl, tcsh, bash, …• Level of Standardization and Portability• Compatibility with Libraries …• Find a good reference on C and/or C++

Operating Systems

• What OS’s are others using to solve your problem?

• What Languages/Libraries are supported

• What do you have access to

• Find yourself a good book on your OS.

Computing Hardware• Does it run the OS you need

• Does it have the hardware attachments you need (Graphics card)

• Is is fast enough, has enough memory, disk space

• Is it accessible by network

• Imbedded processors/ Real time systems, Lap top/Desk top system, Cluster/Batch system, Networked computing

Home Work

• What do you want to do?

• Find a suitable machine you can use

• What are its, OS, Memory, CPU speed, Disk space available, …

I will assume

• You have found a laptop/desktop

• OS: Linux, Mac OS, Windows (with Cygwin), Unix.

• Compiler: GNU, Mac Xcode, Intel.

• Language: C and C++.

Other Things you will need

• Text Editor (ANCI), Emacs, Nedit, MS DOS editor, Xcode,…, pico– Avoid: vi, ed, MS/OpenOffice Word

• Shell window: MS DOS, xterm, …• Subversion:

– Archives with full history code development– Significantly improves code development in

groups.

• X-emulation or native.

A very simple C program/* SimpleProgram.c * Created by Bjorn Nilsen on 5/12/10. * Copyright 2010 Creighton University. * All rights reserved. */#include <stdio.h>int main(int narg,char *argc[]){ double a=3.,b=4.;

printf("a*b=%g\n",a*b);}Note This Blank Line

Compiling and running• gcc SimpleProgram.c

– Creates a file called a.out

• Running the programbjornnilsen% a.out

a*b=12

Bjornnilsen%

• Usually one names the output file the same name as the .c file without any extensions (Linux/Unix), .exe (Windows)

C language

Quick over view

Data Types• void• bool• char• wchar_t• short• int• long• float• double• long double• enum• struct• typedef• class

• signed• unsigned• const• volatile• static• extern• auto• register• union• []• *

All variables must be Defined

Special variablethis

Scope / Name Space

File

Specific files

Block

Program wide

Basics

• Block {}• Function

– Return_type Function_name(argmuments)– Must be declared– No subroutines– Return can be ignored– void main(int argc,char *argv[]) Required

• Lines end with ;• Files end with a blank line

Changing from one type to another. Casting

• double x; int j; x = (double)j;

• x = dynamic_cast<double>j;

• x = static_cast<double>j;

• x = reinterpret_cast<double>j;

Operators• = + - * / % += -= *= /= %= ++ --• && || < <= == != >= > ! ?:• << >> & | &= |= , . -> [] ^ ^= :: ()• * & - + ~ >> << >>= <<=• Default data types, * / + - = must be the same type

– Compiler will introduce type cast as needed

• Comments// line from here on out is a comment/* comment untilthis next pair of symbols*/

Example file

double x;void main(int argc,char *argv[]){ int *i, j=0;// must be here for c code. double y=5.0, *z;

z = &y; {x = y*y; x += x+y; j++; i = &j; // 4 lines *z = (double) (j+ *i);}}

Statements• Empty ;• Declaration double x = 5.0;• Expression j=j+k;• Compound {…}• Try block try {…}• Goto goto l1;• Label l1: …;• If block if(p==0)…; else …;• Switch switch(s){case 1:…; default:…;}• For loop for(I=0;I<10;I++)…;• While loop while(p==0)…;• Do-while loop do …; while(…);• End loop break;• Jump to next loop continue;• Function return return …;

Functions

• Must be declared before use.

• Variables are instantiated at run time, as needed (C++)

• The same function can be called multiple times, Recursion

void MyFunction(double a){

if(b>0.0) MyFunction(b);

}

• There is a limit on how deep you can go

Compiling

• Gcc -Wall -O0 filename.cxx -o filename– -Wall show all warnings– -O0 set optimization to zero– -o filename create output as filename– -g debug information included

• $ filename arguments• $ gcc -Wall -O0 test.cxx test2.cxx -lstdc++ -o test

– -l load library– stdc++ short for libstdc++.so– Preprocessed + compiled + Linked in one step.

• Static linked• Dynamic linked

Libraries

• libstdc.a, libstdc.so, libstdc.dll, libstdc.dyl– “Standard C libraries”

• Input output routines• Character array functions• Memory allocation functions• Math functions

– Each subset has its own include files.

• Many other libraries, some come with your compiler, others are specially made.

C formatted IO

• printf(“%1.1c %10d %6.2f %10.6g text=%s\n”,’c’,1234567890,123.56,1.3456E-90);– sprintf, fprintf,…

• scanf(“%d %g %s”,&j,&d,t); 34891 3.145 SomeText This not inputted– int j; double g; char t[25];– sscanf, fscanf,…

Hello World

int main(int narg,char *varg[]){

printf(“Hello World\n”);

}

Math libraries

Man math for information or check web.

Now write your own c program

Install root from http://root.cern.ch

What does gcc do?• Preprocessing

– Looks for lines starting with #– Performs the text substitution and environment variable

definitions requested.– ROOT has its own additional preprocessor

• Compiling– Compiles based on the requested language– Produces language independent Object code

• Linking– Collects all Object, and library code to produce fully

resolved executable code.– Creates Libraries as requested.

Preprocessing

• Conditionals– #ifdef– #ifndef– #if– #elif– #else– #endif

• Others– #include “…”– #include <…>– #define– #undef– #pargma– #error

Example useInclude file protection

#ifndef MYINCLUDEFILE_H

#define MYINCLUDEFILE_H

#endif

ExampleMacro definitions

#define min(X, Y) ((X) < (Y) ? (X) : (Y))

x = min(a, b);

expands to x = ((a) < (b) ? (a) : (b));

y = min(1, 2);

expands to y = ((1) < (2) ? (1) : (2));

z = min(a + 28, *p);

expands to z = ((a + 28) < (*p) ? (a + 28) : (*p));

Example#if defined __GNUC__

#if __GNUC__ > 2

ios::fmtflags fmt; // Standard IO format object, required for output.

#else

Int_t fmt;

#endif

#else

#if defined __ICC || defined __ECC || defined __xlC__

ios::fmtflags fmt;

#else

Int_t fmt;

#endif

#endif

ROOT Preprocessing

• Adds functions to your class– Binary machine independent ROOT io.– Class dictionary.

• HTML documentation formatting.

Compilation

• Converts code into machine dependent Object code (sometimes compiler dependent).– Optimizes code, replaces your code with

faster code.– Add debugging information– Add profiling information

Linking

• Resolves all remaining variables and references to produce executable code– Can produce libraries, static or shared– Generate machine/OS dependent

executable code.

Could you include a complex type?

• C data structures and typedefstruc{double real;double image;} c0,c1,c2;

can treat this, or any, collection of data as one variable, but could not c0=c1+c2;

• Replace C with C++ and let the user create their own “data” types.C++ Class --- Data structures with function

and operators.

What needs to be done with any data type

• Creation

• Destruction

• Other useful functions– Copy construction– Operator definitions– IO of information– Other useful functions

Used in more places then you think

• MyClass a,b,c,d,e,f,g;

a = b+c*(d+e/f)/g;

MyClass ef; ef = operator/(e,f);

MyClass df; df = operator+(d,ef); destroy ef;

MyClass dg; dg = operator/(df,g); destroy df;

MyClass cg; cg = operator*(c,dg); destroy dg;

a = operator+(b,cg); destroy cg;• Also true for passing variables by value.

Recommended