C Programming
Dr. Eric Frew 11/12/02
Outline
Resources C versus C++ and Java Compilers and Environments Makefiles
Libraries Directories Dependencies
Header files Include files #DEFINES Comments Decomposition and naming
Outline
Structures Typedefs Bitwise and Logical
==, &&, ||, != &, |, xor?
+=, -= Pointers, Arrays Sizeof, bytes Endian
Outline
Resources Differences between Matlab, C, C++, Java Setup and Compiling Syntax
Ask lots of questions. There will be time at end for specific topics I do not cover in my lecture
Resources
The C Programming Language -- ANSI C
By Brian W. C. Kernighan & Dennis M. Ritchie K and R
"Practical C programming"
By Steve Oualline
http://www.physics.drexel.edu/courses/Comp_Phys /General/C_basics/c_tutorial.html http://www.lysator.liu.se/c/bwk-tutor.html
C vs. Matlab
Matlab uses script language = no compiling Matlab can dynamically allocate variables and memory
> x=5 > y = x + 2.5 > x = 2.5 > x = [0.5; 0.4; 1.2];
Matlab functions can return multiple variables
[x, y, t] = ode23(ydot, x0);
C vs. C++ and Java
Object oriented just means
Data encapsulation
Variable is a part of object type, like Structures Can have hidden variables only accessible by methods
Methods
Functions are part of object type Can access object variables or be passed variables
Inheritance
Can inherit variables and methods from parent class
E.g. Animal class has variable color Therefore Dog class has variable color if subclass of Animal
C++ includes all C commands and syntax
Inclusion of precompiled C libraries requires special syntax
Dont worry about it, internal to all standard libraries
Programming Environments
Unix/Linux typically come with gcc
Standard stuff Makefiles
Microsoft Visual Studio
Simplifies compile and link options No Makefile Debugger
Microsoft .Net ? Others
Compile, Link, Execute
All code is compiled and linked to produce executable programs
Compiling translates code into assembly language readable by computer Linking assembles all code, either compiled by you or from other libraries Executables are the programs you run
The following instructions regarding compiling are for command line compilers like gcc, which come with Linux/Unix
Microsoft Developer Studio, etc, use auto-generated Makefiles from menu items
Compile, Link, Execute
An example using gcc to compile fname.c
compile the file fname.c, linked it to the default libraries and produce an executable file called by default a.out
C:/home/> gcc fname.c
Several parameters may be used to modify default
-o out_file -O, -O1, -O2, -O3 -c fname.c -lname -Ldirectory specify the output file (executable, or binary) to be out_file specify optimization level indicates that you only want to compile the file fname.c, in which case the output file will be
fname.o
links with the library libname.a directs gcc to look for libraries in directory, in addition to the standard system library path
C:/home/> gcc fname.c o UAVflight lmathutil L/home/utils
Makefile
A makefile is used to specify parameters for one or more set of files
File is called Makefile From directory with Makefile
C:/home/> make C:/home/> gmake
Can make certain targets only
C:/home/> make all C:/home/> make clean
Makefile
Variable Definitions
CFLAGS = -g -Wall SRCS = main.c file1.c file2.c CC = gcc main.o: main.c main.h gcc -g -Wall -c main.c CFLAGS = -g Wall
Dependency Rules
main.o is created if main.c or main.h has changes In order to compile main.o the second line is used as command Second line must have a tab
Comments
# A number sign denotes a comment
Makefile - Example
# top-level rule to compile the whole program. all: prog # program is made of several source files. prog: main.o file1.o gcc main.o file1.o -o prog # rule for file "main.o". main.o: main.c file1.h gcc -g -Wall -c main.c # rule for file "file1.o". file1.o: file1.c file1.h gcc -g -Wall -c file1.c # rule for cleaning files generated during compilations. clean: <- can have rule for other /bin/rm -f prog main.o file1.o file2.o commands besides compiling <- uses first rule if no target specified <- object can be dependent on more than one file <- object can be dependent on header files
CC = gcc LD = gcc CFLAGS = -g -Wall LDFLAGS = RM = /bin/rm -f OBJS = main.o file1.o PROG = UAVFlight LIBS = mathutil, camcal LIBDIRS = /home/utils/ # top-level rule, to compile everything. all: $(PROG) # rule to link the program $(PROG): $(OBJS) $(LD) $(LDFLAGS) $(OBJS) -o $(PROG) # rule for file "main.o". main.o: main.c file1.h $(CC) $(CFLAGS) -c main.c
<- Now have variables to define terms
<- $(variable) replaced by value when compiled
# rule for file "file1.o". file1.o: file1.c file1.h $(CC) $(CFLAGS) -c file1.c l$(LIBS) L$(LIBDIRS) # rule for cleaning re-compilable files. clean: $(RM) $(PROG) $(OBJS)
Makefiles
More information online at
http://users.actcom.co.il/~choo/lupg/tutorials/writing-makefiles/writing-makefiles.html
I ALWAYS copy an old Makefile rather than starting from scratch
Header Files
Header files allow your code to know about other functions provided by other code, e.g libraries, other .c files, or standard libraries
#include <math.h> #include myfile1.h <- brackets indicate standard library <- filename can be given if directory listed in Makefile <- Otherwise full path required
#include C:\home\code\myfile2.h
Good coding practice
Define all constants at top of file with macro
Constants are typically all caps
#define PI (3.14159) #define D2R (PI/180.0) sin(D2R*45) => sin((PI/180.0)*45) => sin(((3.14159)/180.0)*45)
Comments
Use comments to leave notes to self and others about code functionality
// double slash marks a comment of a single line /* The slash then star marks the beginning of a multi-line comment while the star then slash marks the end of the comment */
Decomposition and Naming
Make function and variable names descriptive
v1, v2, v3, are bad position_x, position_y, position_z are better
Programming classes will teach you that one function should have 3-10 lines total
Otherwise decompose into smaller functions
void main () { InitializeRobot(world_map); while(robot==on) { DriveRobot(world_map); } ShutdownRobot(); }
Structures
Structures are a way of bundling data together, especially different types
Similar to C++ or Java classes, but not as powerful
Can be passed into or returned by function
struct image_feature { double x; double y; int size; }; void main() { struct image_feature object1, obj_array[5]; object1.x = 5.0; object1.y = 6.0; object1.size = 8; object1 = Calibrate(object1); } object3[3].x = 5.0;
Structures
Can use pointers to structures
Dereferenced differently
void main() { struct image_feature *object_ptr; object_ptr->x = 5.0; object_ptr->y = 6.0; object_ptr->size = 8;
Typedef and Enum
Typedef allows you to create your own variable type and simplify names
typedef struct { double x; double y; int size; } image_feature_type; image_feature_type object2
Enum allows you to create a list of numbers and assign them variable names
enum e_data_pkt { GPS=1, IMU, SPEED, ACK, NAK}; typedef enum e_data_pkt pkt_type; current_data.pkt_type = IMU;
Syntax
All C programs begin with a main function
Windows based programs slightly different
void main() { printf(Hello World\n); }
Main can have command line arguments
argc = number of arguments argv = array of strings
void main(int argc, char *argv[] ) { C:/home/> UAVFlight v if (argc==1) C:/home/> UAVFlight l logfile.log if (strcmp(*argv, -v)) verbosity = 1; }
Syntax
All lines end with a semicolon
void main() { int x,y; x = 3*y*y + 5*y + 25; } <= Equivalent => void main() { int x,y; x = 3*y*y + 5*y + 25; }
Sections are denoted by curly brackets
if (x==1) { y = 2*x; z = 2.5*x; } else { y = 3*x; z = 1.5*x; }
Variable types
Variables must be created and typed
Cannot dynamically create variables like in MATLAB
MATLAB: > x=5 > y = x + 2.5 > x = 2.5 C: void main() { int x; float z; x = 5; x = 6*x; z = 2.5*x; x = 6.0*x;
<- 6 is int <- 6.0 is float
Beware integer math
Rounds down (3 / 4 = 0) Automatically converts to float if any variable is float
Symbols
Do not confuse logical symbols with others
== ! != && || = ~ & | ^ << >> logical equal logical not Not equal logical and logical or if (x==5) if (!flag) if (x!=5) if((x==5)&&(y==2)) if((x==5)||(y==2))
assignment x=5 bitwise not ~0xf0 bitwise and 0x3e & 0xf0 bitwise or 0x3e | 0xf0 bitwise xor (exclusive or) 0x3e ^ 0xf0 bitwise left shift 0x3e << 2 bitwise right shift 0x3e >> 2
<=
00111110 & 11110000 --------------00110000
Assignment
Standard arithmetic operators (+,-) can be combined with assignment (=)
int x,y,z; x = 5; x =+ 6; // x now equals 11 (5 + 6) x =- 10; // space matters, x now equals 1 (11 10) x = -10; // x now equals -10 x++; //x now equals -9 (-10 + 1)
If, else, while
If and else used as expected
if (condition1){ // execute code } else if (condition2) { // execute different code } else { // execute even different code }
While and for are used to loop
int i=0; for (int i=0; i<MAX_ITERS; i++) { while (i<MAX_ITER{ // execute code <= Equivalent => // execute code } i++ }
Pointers and Arrays
Aaarrgh, hardest part of programming (if you ask me) A pointer is an address of something Denoted by * in declaration
int x,z, *y; x = 5; y = &x; // & means address of, so y is address of x z = *y; // * means what is at, so z = 5 because x = 5
Big Endian, Little Endian
Byte order in memory depends on processor Little endian means low-order byte number is stores at lowest memory location
Intel chips (PCs)
Big Endian means highest-order byte is stored at lowest memory address
Motorola (Macs)
This is an issues if data is written to files or sent over a network Certain formats (e.g. jpeg) require specific formats
Big Endian, Little Endian
An integer is four bytes [Byte 3, Byte2, Byte1, Byte 0] Ex. 257 = [00000000 00000000 00000010 11111111] Little Endian Base Address+0 Base Address+1 Base Address+2 Base Address+3
Byte Byte Byte Byte
0 1 2 3
11111111 00000010 00000000 00000000
Big Endian Base Address+0 Base Address+1 Base Address+2 Base Address+3
Byte Byte Byte Byte
3 2 1 0
00000000 00000000 00000010 11111111
Recommendations
Copy old Makefiles dont start from scratch Use #defines and enums
Avoid magic numbers that have no context
Variable and function names must be meaningful There is no such thing as too many comments
You might forget after several months what is supposed to happen or your teammates may need to make changes in your absence
Break code down into different functions and files that can be compiled and tested independently
Last Words
Use command line arguments as opposed to recompiling
Especially for parameters that are changed frequently
Pay attention to pointers
C will de-reference the wrong place if you tell it too
The computer will always do what you tell it to do. - Its just not always what you want it to do!
Programming is 10% coding, 90% debugging. -Dont expect your code to work the first time.