A "Crash Course" To (Matlab And) C Programming For TTT4225
A "Crash Course" To (Matlab And) C Programming For TTT4225
CREDITS
The C-programming part is heavily derived from:
Lewis Girod
CENS Systems Lab
http://lecs.cs.ucla.edu/~girod/talks/c-tutorial.ppt
1
2
Tentative Time Schedule
3
Some Notes on the “Crash Course”
4
Matlab?
5
Functions in Matlab
6
Matlab Help - aka. The Scientist’s Best Friend
7
Structures in Matlab
struct: Very close to the ‘struct’ data type in C; also reminds an object of
the OO programming languages, but cannot contain methods. A structure
consists of fields that can contain any kind of data. A structure can be
passed to a function as an argument, but be careful with the field names.
>>opt=struct('gamma',0.9,'nbits',4)
opt =
gamma: 0.9000
nbits: 4
0.9000
gamma: 0.9000
nbits: 4
Struct is a good data type to collect related
alpha: 0.9000 variables together in one place.
8
Some Matlab Functions That May Come in Handy
9
Final Notes on Matlab
10
C Compiler
11
A Quick Digression About the Compiler
#include <stdio.h>
__extension__ typedef unsigned long long int __dev_t; In Preprocessing, source code is “expanded” into
__extension__ typedef
__extension__ typedef
unsigned int
unsigned int
__uid_t;
__gid_t; a larger form that is simpler for the compiler to
__extension__ typedef
__extension__ typedef
unsigned long int
unsigned long long int
__ino_t;
__ino64_t;
understand. Any line that starts with ‘#’ is a line
__extension__ typedef
__extension__ typedef
unsigned int
long int
__nlink_t;
__off_t; that is interpreted by the Preprocessor.
__extension__ typedef long long int __off64_t;
extern void flockfile (FILE *__stream) ;
extern int ftrylockfile (FILE *__stream)
extern void funlockfile (FILE *__stream)
;
; • Include files are “pasted in” (#include)
int main(int argc, char **argv)
{ • Macros are “expanded” (#define)
printf(“Hello World\n”);
return 0;
• Comments are stripped out ( /* */ )
}
• Continued lines are joined ( \ )
\?
12
Writing and Running Programs
#include <stdio.h>
/* The simplest C Program */
int main(int argc, char **argv)
{
1. Write text of program (source code) using an editor
printf(“Hello World\n”);
return 0;
such as emacs / vim, save as file e.g. my_program.c
}
13
C Syntax and Hello World
#include <stdio.h>
The main() function is
/* The simplest C Program */ always where your program
int main(int argc, char **argv) starts running.
{
Blocks of code (“lexical
printf(“Hello World\n”); scopes”) are marked by { … }
return 0;
}
Return ‘0’ from this function Print out a message. ‘\n’ means “new line”.
14
Standard Header Files and Libraries
$ cat /usr/src/include/stdio.h
[lots of code precedes]
int fprintf(FILE * __restrict, const char * __restrict, ...);
[lots of code follows]
15
Custom Header Files?
#ifndef __TALKTHROUGH_H__
To avoid declaring same functions #define __TALKTHROUGH_H__
or variables multiple times. Use in
multi-file programs. #include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <string.h>
#include "talkthrough.h”
#define HDRDATATYPE int8_t
[... code …] #define INPUTDATATYPE int16_t
#define OUTPUTDATATYPE int16_t
int main(int argc, char **argv){ #define HDRLEN 44
talkthrough.c #endif
talkthrough.h
Why custom header files?
16
OK, We’re Back.. What is a Function?
#include <stdio.h>
Function Arguments
/* The simplest C Program */
int main(int argc, char **argv)
Calling a Function: printf() is just
{
another function, like main(). It’s defined
printf(“Hello World\n”); for you in a “library”, a collection of
return 0; functions you can call from your program.
}
Returning a value (0 == EXIT_SUCCESS in <stdlib.h>)
17
What is “Memory”?
18
What is a Variable?
symbol table? -g
19
Multi-byte Variables
20
Talkthrough.tar.gz
abyss% ./talkthrough –h
abyss% ./raw2wav -h
21
Scopes, mathematical operations, assignment, more Thu 12.2.
on memory and recursive functions, loops, pointers
22
Lexical Scoping (Returns nothing)
void p(char x)
Every Variable is Defined within some scope. {
A Variable cannot be referenced by name char y;
/* p,x */
legal?
char d;
The scope of Variables defined outside a /* p,z,q,a,b,d (not c) */
function starts at the definition and ends at }
23
Comparison and Mathematical Operators
24
Assignment Operators
25
if Statement and Recursive Function
#include <stdio.h>
/* if evaluated expression is not 0 */ #include <inttypes.h>
if (expression) {
/* then execute this block */ float pow(float x, uint32_t exp)
} {
else { /* base case */
/* otherwise execute this block */ X?Y:Z if (exp == 0) {
} return 1.0;
}
/* “recursive” case */
Remember the parenthesis and the return x*pow(x, exp – 1);
curly braces. }
26
Note On The “Stack” And Recursive Functions
#include <stdio.h>
Each function call allocates a “stack frame” #include <inttypes.h>
where variables within that function’s scope float pow(float x, uint32_t exp)
will reside. {
/* base case */
if (exp == 0) {
return 1.0;
Problem: “recursion” eats stack space (in C). }
Each loop must allocate space for arguments
/* “recursive” case */
and local variables, because each new call return x*pow(x, exp – 1);
}
creates a new “scope”.
int main(int argc, char **argv)
{
float x 5.0 float p;
uint32_t exp 0 Return 1.0 p = pow(5.0, 1);
printf(“p = %f\n”, p);
float x 5.0 return 0;
}
uint32_t exp 1 Return 5.0
int argc 1
while (condition) {
char **argv 0x2342 statements;
float p undefined
5.0
Grows }
27
The “for” Loop
The “for” loop is just shorthand for this “while” loop structure.
28
Can a Function Modify Its Arguments?
29
NO!
float x 2.0
32.0
uint32_t exp 5
float result 1.0
32.0
30
Passing Addresses – Pseudo Code
void f(address_of_char p)
8
{
/* Modify the content of memory */
9
memory_at[p] = memory_at[p] - 32;
}
10
f(address_of(y)); /* i.e. f(5) */ 11
/* y is now 101-32 == 69 */
12
31
“Pointers”
32
Pointer Validity
A Valid pointer is one that points to memory that your program controls.
Using invalid pointers will cause non-deterministic behavior, and will
often cause Linux to kill your process (SEGV or Segmentation Fault).
There are two general causes for these errors: Always initialize pointers to NULL!
• Program errors that set the pointer value to a strange number
• Use of a pointer that was at one time valid, but later became invalid
char * get_pointer()
{
char x=0;
return &x;
}
{
char * ptr = get_pointer();
*ptr = 12; /* valid? */
}
33
Answer: Invalid!
char * get_pointer()
{
char x=0;
return &x;
} But now, ptr points to a
{
location that’s no longer in
char * ptr = get_pointer(); use, and will be reused the
*ptr = 12; /* valid? */
other_function(); next time a function is called!
}
101 charaverage
int x Return
0 101
12
456603
34
Arrays, structures, types, dynamic memory allocation, Wed 18.2.
bit-wise operations, makefile, task related issue.
35
Arrays in Matlab and C
Matlab C
• Elements of x: • Elements of x:
x(1), x(2),…, x(N) x[0], x[1],…, x[N-1]
• Elements of y: • Elements of y:
y(1,1),…, y(N,M) y[0][0],…, y[N-1][M-1]
• Arrays can be passed as • Arrays are passed to
arguments in funtions. functions via their address.
• Commands like: • Copying of arrays via loops,
z = y(:,1); z = zeros(3); memcpy, etc. Initialization:
are possible. double z[3]={42,666,69};
double z[3];
Arrays are not automatically
initialized, e.g., to zero
36
Arrays in C
37
Arrays and Pointers
Arrays and pointers are very much related. Especially, when you pass
an array to a function as an argument, it is interpreted as passing the
memory address of the first element in the array.
talkthrough.c
int x[100];
int *y = NULL;
y = (int *) malloc((ysize)*sizeof(int));
Dynamic memory
allocation. More later.
Process_Data(x, y, 100);
Process_Data(&x[0], &y[0], 100);
void Process_Data(int *x, int *y, int nread) Note that you can use the
{
unsigned int i; pointers as arrays here.
for (i = 0; i < nread; i++)
y[i] = x[i];
Another option would be:
} *(y+i) = *(x+i);
process_data.c
38
How to Parse and Define C Types
At this point we have seen a few basic types, arrays and pointer types.
So far we’ve glossed over how types are named.
C type names are parsed by starting at the type name and working
outwards according to the rules of precedence:
x is
an array of
pointers to
int *x[10]; int
Arrays are the primary
source of confusion. When
x is in doubt, use extra parens to
int (*x)[10]; clarify the expression.
a pointer to
an array of
int
39
Structures
40
Dynamic Memory Allocation
41
Caveats with Dynamic Memory
Whereas the compiler enforces that reclaimed stack space can no longer
be reached, it is easy to accidentally keep a pointer to dynamic memory
that has been freed. Whenever you free memory you must be certain that
you will not try to use it again. It is safest to erase any pointers to it.
42
Some Common Errors and Hints
sizeof() can take a variable reference in place of a type name. This gurantees the right
allocation, but don’t accidentally allocate the sizeof() the pointer instead of the object!
43
Reading and Writing Files in C
[… code …]
[… code …]
fclose is the counterpart of fopen, i.e., it
closes the file and deletes the pointer.
44
Macros
Macros and static inline functions must be included in any file that
uses them, usually via a header file. Common uses for macros:
45
Some Task Specific Notes
main() main()
{ {
unsigned int a = 60; /* 60 = 0011 1100 */ /* 4 = 0000 0100 */
unsigned int b = 13; /* 13 = 0000 1101 */ unsigned int Value=4;
unsigned int c = 0; unsigned int Shift=2;
The “cyclic buffer” allows you to save memory in the real-time enviroment
by overwriting the already used data. Especially useful for the up/
downsampling part.
46
Simple Makefile
Assume
we
have
files:
hellomake.c,
hellofunc.c
and
hellofunc.h
in
our
project.
#include “hellofunc.h"
return(0);
}
A makefile contains the “rules” how the system has to be compliled. A program
called make reads the Makefile (default name), parses it and calls the
compiler / linker appropriately. Here’s a simple makefile for the above system:
$ info make
hellomake: hellomake.c hellofunc.c
gcc hellomake.c hellofunc.c –o hellomake –I.
The
first
line
contains
all
files
the
program
is
depends
on.
This
is
used
by
make
to
decide
which
files
have
changed
and
need
to
be
re-compiled.
NOTE:
The
lines
not
having
target:
have
to
start
with
’tab’-character.
47
More Sophisticated Makefile
TALKTHROUGH_TRG = talkthrough
TRGS = $(TALKTHROUGH_TRG) Compiler, flags and files as macros. If
you add / remove files from your project
OTHER_OBJS_TT = process_data.o tools.o you need to change these macros.
OBJS = $(TALKTHROUGH_TRG).o $(OTHER_OBJS_TT)
48
The Wave Format
http://ccrma.stanford.edu/courses/422/projects/WaveFormat/
000358_JF.wav
[4] ChunkID = 52 49 46 46 ("RIFF")
[4] ChunkSize = 24 d5 02 00 = 0x0002d524 (185636)
[4] Format = 57 41 56 45 ("WAVE")
04 00 03 00 04 00 fe ff ...
49