Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

SystemC-n-BehaviorCoding_Fall2021_Section2_C

Uploaded by

Hua-Chien Chang
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

SystemC-n-BehaviorCoding_Fall2021_Section2_C

Uploaded by

Hua-Chien Chang
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 68

+

SystemC, Behavior Coding


and Modeling
蘇培陞 博士
Alan P. Su, Ph.D.
alansuphd@cs.nthu.edu.tw, alansuphd@mail.ncku.edu.tw
+
2

Drag picture to plac

Section 2
C Programming Language

Drag picture to plac


+
C

 A general purpose programming


language developed by Dennis
Ritchie circa 1969 and 1973 at Bell
Labs
 The native language of Unix
 The most widely used language, both
in applications and embedded
systems programming
 It can embed assembly code directly
+ 4

The C Book
 Dennis M. Ritchie (1941~2011) &
 Brian W. Kernighan (1942~, also
the creator of “Hello World”)
 Published by Prentice Hall,1988
 Unix was developed by Ritchie and
Kenneth L. Thompson (1943~)

Thompson Ritchie Kerninghan


+ 5

# Preprocessor

# is a preprocessor keyword
 #define A 100 // to define a keyword
 #include “type.h” // to include a user code
// segment
 #include <systemc.h> // to include a system
code // segment
 #ifdef A // examine a defined
keyword
 #else // else to #if
+ 6

#include

 Syntax
#include “filename”
#include <filename>
 To include a file into the code
 Usually to include a header file, i.e. .h file
 But you can include another C source code too, or
anything you want

Examples
#include <stdio.h> // search the –L path
#include “src.h” // search current dir
// then the –L path
+ 7

#define
 Syntax
 #define identifier token-sequence
 Token-sequence: a sequence of tokens, i.e. text block
ended by \n (new line)

 Example
#define VER 1.0 // a define with value
#define HEADER // a define without value
#define max(A, B) ((A) > (B) ? (A) : (B)) // macro

i.e. (A) > (B) ? (A) : (B) means


if (A > B)
output A
else
output B
+ 8

A Side Note Regarding ( )

 Why all the parenthesis in


(A) > (B) ? (A) : (B)
 Consider the following:

#define square(x) x*x


then
square(z+1) becomes z+1*z+1 = z+z+1

#define square(x) (x)*(x)


now
square(z+1) becomes (z+1)*(z+1)
+ 9

#if #elif #else #endif


 To
check if a keyword is defined or what is the
defined value

 Example
#if SYSTEM == SYSV
#define HDR “sysv.h”
#elif SYSTEM == BSD
#define HDR “bsd.h”
#elif SYSTEM == MSDOS
#define HDR “msdos.h”
#else
#define HDR “default.h”
#endif
+ 10

#ifdef #ifndef
 #ifdefchecks if a keyword is defined
 #ifndef checks if a keyword is not defined

 Example
#ifdef SYS
#else
#include “sys.h”
#endif

 In sys.h:
#ifndef SYS
#define SYS
/* content of sys.h here */
#endif
+ 11

Header file

 Header file, or .h file, is a code segment to define variables,


classes, and include other header files
 Header file is not a must. But it is a good practice and coding
style to isolate definitions from the source code: information
hiding and modulation
 Exp:
#include <stdio.h> // include a library header
#include “other.h” // include other source headers
class aClass {
int A, B, C; // data members
int increase(int); // member function
}; // class definition
+ 12

Source Code

 The code body, which implements main and other


functions
 Any self-sustained executable code must has exactly
one (one and only) main function
+ 13

Compilation

 When we say ‘compilation’ we usually refer to two


steps: compile and link (a.k.a linking, linkage)
 Compile is to check whether the source code is legal
versus syntax and semantics
 Link is to resolve all naming and pull in all libraries.
During the process further semantics is checked
 For standalone executable then the main function must be
linked in as well
+ 14

Object code

 The output of a compiled source code. An object code


not necessary to contain main function
 g++ -c src.cpp

 Thus, the object file src.o is created


+ 15

Link

 Linking object codes


 The output can be an executable code, or a library (.a
or .so file)
 An executable must contain the main function
 Library is a collection of linked functions. However, it must
further linked with a main function to execute

 Exp
 g++ srca.o srcb.o main.o –o a.out

 Compile a library
 ar rcs libmylib.a objfile1.o objfile2.o objfile3.o
+ 16

The main function

int main(int argc, char *argv[])


{

}
 A function called main, with inputs an integer variable, and
an array of character type arrays, then outputs an integer
 The input integer variable is to indicate the number of input
arguments, and the array of these arguments
 a.out John is a nice person
 Executable plus 5 control commands, therefore argc = 6
 argv = {a.out, John, is, a, nice, person} –
notice that a.out, John, is, a, nice, person are 6
character arrays, and thus argv is typed char**
+ 17

Assignment 1, Problem 1
A hello world code
#include <stdio.h>
int main(int argc, char *argv[]) {
// please add a printf statement before
// the following printf, that prints the
// name of the executable plus ‘says’
// To print a character array, the formatted
// output is
// printf(“%s”, str);
// where str is declared as, say, char str[20];
printf(“Hello World!\n”);
exit(0);
}
 For
example, the executable is named run. So,
when run get executed the output becomes:
run says Hello World!
+ 18

Declaration

 A variable must be declared first then to be used in


statements
 A good coding style is to have variables declared in the
first section of a function (notice that main is also a
function,) which we called the declaration section
 However, to narrow the lifetime of variables, it is a good
idea to declare local variables as close to their use as
possible

 Declare data structure in header files


+ 19

A Declaration Example

int main(int argc, char *argv[])


{
int i1, i2, i3;
char s1, s2, s3;
float f1, f2, f3; // above is declaration

i3 = i1 + i2; // a statement that uses


// i1, i2 and i3
for (int i=0; i<10; i++) {
.... // i is declared right before
} // its use
}
+ 20

Data Structure
 Simply put, data structure is the collection of data
and registers needed in an algorithm
 For example, to do bubble sort, one needs an array
to store data, then a temporary register for
swapping two elements
// bubbleSort.h
#ifndef BUBBLE
#define BUBBLE

int data[100]; // sort 100 data


int swap; // swap register

void bubbleSort(int *); // function definition

#endif
+ 21

Data Types

 int 32-bit integer


 long 32-bit integer
 long long64-bit integer (at least)
 short 16-bit integer
 char 8-bit (byte)
 float single precision floating point
 double double precision floating
point
 unsigned int
 unsigned long
 unsigned long long
 unsigned short
 unsigned char
+ 22

Math & Logical Operators

 Mathematical
 + binary add, e.g. a = a + b;
 += unary add, e.g. a += b;
 - binary subtract, e.g. a = a – b;
 -= unary subtract, e.g. a -= b;
 * binary multiply, e.g. a = a * b;
 *= unary multiply, e.g. a *= b;
 / binary divide, e.g. a = a / b;
 /= unary divide, e.g. a /= b
 % modula. a % b = the remainder of a divide by b
 ++ unary increment, e.g a++;
 -- unary decrement, e.g. a--;

 Logical
 && And, e.g. (a > b) && (b < c)
 || Or, e.g. (a > b) || (b < c)
+ 23

Relational Operators

 > Greater than


 >= Greater than or equal to
 == Equal to
 != Not equal to
 <= Less than or equal to
 < Less than
+ 24

Bitwise Operators

 & bitwise AND


 | bitwise inclusive OR
 ^ bitwise exclusive OR
 << left shift
 >> right shift
 ~ one’s complement (unary)
+Most Commonly Used 25

String Functions in string.h

Function Use
strcat(s,t) Concatenate t to end of s
strncat(s,t,n) Concatenate n characters of t to end of s
strcmp(s,t) Return negative, zero, or positive for
s < t, s == t, or s > t
strncmp(s,t,n) Same as strcmp but only in first n characters
strcpy(s,t) Copy t to s
strncpy(s,t,n) Copy at most n characters of t to s
strlen(s) Return length of s
strchr(s,c) Return pointer to first c in s, or NULL if not present
strrchr(s,c) Return pointer to last c in s, or NULL if not present
+Character Testing and Conversion 26

in <ctype.h>

Function Use
isalpha(c) Non-zero if c is alphabetic, 0 if not
isupper(c) Non-zero if c is upper case, 0 if not
islower(c) Non-zero if c is lower case, 0 if not
isdigit(c) Non-zero if c is digit, 0 if not
isalnum(c) Non-zero if isalpha(c) or isdigit(c), 0 if not
isspace(c) Non-zero if c is blank, tab, newline, return, formfeed,
vertical tab
toupper(c) Return c converted to upper case
tolower(c) Return c converted to lower case
+Statement LHS & RHS, and 27

Evaluate & Update

 A simple statement
a = b + c; // Left-Hand-Side (LHS) and
// Right-Hand-Side (RHS)
// RHS is ‘evaluated’ first
// then LHS is ‘updated’
 An assignment statement
x = y; // Updates RHS to LHS
// However, RHS is still being
// evaluated first
+ 28

if Statement

if (i > 0)
“i > 0” is an expression. And in this case, a
comparison expression. If the expression is true, then the
code segment controlled by this ‘if’ is executed. If false
then no execution

if (i < 0) // when i is less than 0


{}
else if (i == 0) // when i equals 0
{}
else // when i is greater than 0
{} // this is concluded out of
logic
+ 29

Truth Value of An Expression

if (0)
a = b + c; // will this statement be
// executed, ever?

if (1)
x = y * z; // will this statement be
// executed, ever?

if (a = b)
r = s / t; // will this statement be
// executed, ever?
+
? : Expression

 A way to write a simple if-else

expr1 ? expr2 : expr3

equals to

if (expr1)

 Example
+ 31

for, A Loop Statement

for (expr1; expr2; expr3)


statement
 expr1: initial condition
 expr2: loop condition
 expr3: stepping calculation

Example

for (i = 0; i < n; i++) { // Left brace


a[i] = i * 2; // Single statement do not
// need braces
} // Right brace
+ 32

Assignment 1, Problem 2

 A hello world code

#include <stdio.h>
int main(int argc, char *argv[]) {
printf(“Hello World!\n”);
// add a loop below to print input arguments,
// if any. Print a space after each input
// argument. When all input arguments are
// printed, print a newline
….
exit(0);
}

Assume the executable is named echo. Give


echo I am a good student
we get
Hello World!
I am a good student
+ 33

A Forever Loop

for ( ; ; )
statement

This loop never ends, unless there is a break statement inside to


break out of the loop

Notice that a statement has two basic forms. For example:

a = b + c; // a single line statement

{ // a compound statement quoted


b = 3; // by braces for data scope
c = 5;
a = b + c;
}
+ 34

while, A Loop Statement


while (expr)
statement

Repeat the statement while expr is true. If expr is false before


the while, the statement does not execute at all

for (expr1; expr2; expr3)


statement

Is identical to

expr1;
while (expr2) {
statement
expr3;
}
+ 35

do while, A Loop Statement

do {
statement
} while (expr);

Unconditionally execute the statement once then check


for the condition expr

i = 0;
do {
i = i + 1;
} while (i < 10);
+ 36

switch Statement
switch (expression) {
case const-expr: statements
case const-expr: statements
default: statements
}

Note: if no break at the end of a case statement, it will continue the


execution to next case statement
Note: default is a good habit to catch all other cases

Example
char c;
switch (c) {
case ‘0’: printf(“0\t”);
break;
case ‘1’: printf(“1\t”);
break;
default: printf(“\n”);
}
+ 37

Pointer

 Pointer is a variable that stores address value


 Pointers can be calculated with all math, logical and
binary operators

Example:

int *a; // a is an integer pointer


int b, c;

a = &b; // now a points to b


c = *a; // get the value of b and assign to c
+ 38

Pointer and Array

 The array name is a pointer

int A[10]; // A is typed int*


int B[5][10]; // B is typed int**
int* Addr; // An integer pointer

Addr = A; // Addr now points to A


for (int i = 0; i < 10; i++) {
B[0][i] = *Addr; // get A[] values
Addr++; // to the next cell
}
+ 39

Function - Introduction

 A function must first to be declared then to be


implemented
 Pass-by-value: pass values directly into the function
 With pass-by-value a function can have one return
value
 However you may return more values using pass-by-
reference, i.e. pass the pointer
+ 40

Pass by Value

int func(int, int); // function declaration


// passes in 2 integers
// and returns an integer

int func(int a, int b) // implementation


{
return a + b; // returns the value of
// a + b
}
+ 41

Pass by Reference 1

int func(int, int, int*); // function declaration


// passes in 2 integers
// and returns an integer

int func(int a, int b, int *c) // implementation


{
*c = a + b; // result is passed into c
// by reference
return 0; // returns a success flag
}
+ 42

Pass by Reference 2 - C++ only

int func(int&, int&, int&);


// all parameters are
// pass-by-reference

int func(int& a, int& b, int& c)


{
c = a + b; // input can also be
// passed by reference
return 0; // returns a success flag
}
+ 43

Callback Functions

 A callback is a piece of executable code that is passed


as an argument to other code, which is expected to call
back (execute) the argument at some convenient time.
 Programming languages support callbacks in different
ways, often implementing them
with subroutines, lambda expressions, blocks,
or function pointers.
 In all cases, the intention is to specify a function or
subroutine as an entity that is, depending on the
language, more or less similar to a variable.
+ 44

Callback Function in C
#include <stdio.h>
#include <stdlib.h>

/* The calling function takes a single callback as a parameter. */


void PrintTwoNumbers(int (*numberSource)(void)) {
printf("%d and %d\n", numberSource(), numberSource());
}

/* A possible callback */
int overNineThousand(void) { return (rand() % 1000) + 9001; }

/* Another possible callback. */


int meaningOfLife(void) { return 42; }

/* Here we call PrintTwoNumbers() with three different callbacks.


*/
int main(void) {
PrintTwoNumbers(&rand);
PrintTwoNumbers(&overNineThousand);
PrintTwoNumbers(&meaningOfLife);
return 0;
}
+ 45

Formatted Output

 Standard output library function


 printf ( char *format, arg1, arg2, …);
 format is a string and must be quoted by “ ”
 Example “John’s score is %d, Mary’s is %d\n”
 where %d is the conversion specification for data in decimal integer
format, and \n is an escape sequence, new line
 The complete example:
int Jsc = 95;
float Msc = 96.5;
printf(“John’s score is %d, Mary’s is %f\n”, Jsc, Msc);

And the output is


John’s score is 95, Mary’s is 96.5
+
Output Conversion Specifications
Comprised of a leading % and followed by a conversion
character
Character Argument type; Printed as
d, i int; decimal number
o int; unsigned octal number (without a leading 0)
x, X int; unsigned hexadecimal number (without a leading 0x or 0X),
using abcdef or ABCDEF for 10~15
u int; unsigned decimal number
c int; single character
s char *; print characters from the string until a ‘\0’ or the number of
characters given by the precision
f double; [-]m.dddddd, where the number of d’s is given by the
precision (default 6)
e, E double; [-]m.dddddd e±xx or [-]m.ddddddE±xx, where the number of d’s is
given by the precision (default 6)
g, G double; use %e or %E if the exponet is less than -4 or greater than
or equal to the precision; otherwise use %f. Trailing zeros and a
trailing decimal point are not printed
p void *; pointer (implementation-dependent representation)
% No argument is converted; print a %
4
6
+ 47

Formatted Input

 Standard output library function


 scanf ( char *format, arg1, arg2, …);
 format is a string and the same as output except for
conversion specifications
 Arguments are pointers
 The complete example:

int arg1;
float arg2;
scanf(“%d %f\n”, &arg1, &arg2);
+
Input Conversion Specifications
Comprised of a leading % and followed by a conversion
character
Character Input data; Argument type

d Decimal integer; int *

i Integer; int *. The integer may be in octal (leading 0) or hexadecimal


(leading 0x or 0X)
o Octal integer (with or without leading zero); int *

u Unsigned decimal integer; unsigned int *

x Hexadecimal integer (with or without leading 0x or 0X); int *

c Characters; char *. The next input characters (default 1) are placed at


the indicated spot. The normal skip over white space is suppressed; to
read the next non-white space character, use %1s.
s Character string (not quoted): char *, pointing to an array of characters
large enough for the string and a terminating ‘\0’ that will be added
e, f, g Floating-point number with optional sign, optional decimal point and
optional exponent; float *.
% Literal %; no assignment is made

4
8
+ 49

Escape Sequence
To be used in I/O for formatting control. Always led by a \

Control Use Control Use


Sequence Sequence
\a Alert (bell) character \\ Backslash
\b Backspace \? Question mark
\f Formfeed \’ Single quote
\n Newline \” Double quote
\r Carriage return \ooo Octal number
\t Horizontal tab \xhh Hexadecimal number
\v Vertical tab
+ 50

File I/O

 First include <stdio.h>


 File handler type is FILE *. So declare one
 Open the file using
 FILE *fopen(char *name, char *mode);
 Modes: r (read), w (write), a (append), b (binary)

Example

#include <stdio.h>
FILE *fp1, *fp2;
int arg1;
float arg2;

fp1 = fopen(“file1”, “r”); // open the file for reading


fp2 = fopen(“file2”, “a”); // open the file for appending
fscanf(fp1, “%d %f\n”, &arg1, &arg2);
fprintf(fp2, “Copy integer %d, float %f\n”, arg1, arg2);
+
51

Drag picture to plac

Section 2-1
Advanced Topics in C

Drag picture to plac


+
Drag picture to placeholder or click ico

Not “English as
Second Language”
Drag picture to plac

strtok

5
2
+ 53

char* strtok(char*, const char*)


#include <string.h>
#include <stdio.h>

int main()
{
char str[]=“104.99.34.251";
char *delim = “.";
char * tok;

printf (“Break string \"%s\" into


tokens:\n",str); First time
tok = strtok(str,delim);
while (tok != NULL)
{
printf ("%s\n",tok);
tok = strtok (NULL, delim); Second
} time and
return 0; later
}
+ 54

Execution Result
Breaking string 140.99.34.251 into tokens:

140

99

34

251
+ 55

Assignment 2, Problem 1
 Text processing
 Open a file (the text file) by command input, e.g. run
TheTextFile
 Implement a function to count in the file
 How many lines
 How many characters
 How many upper case letters
 How many words

 Then implement another function that turns all the text


into upper case and writes to a file named “UPPER”
+
Drag picture to placeholder or click ico

Not “English as
Second Language”
Drag picture to plac

Pointers to Functions

5
6
+ 57

Pointers to Functions

 In C, a function itself is not a variable, but it is possible


to define pointers to functions, which can be
 assigned,
 placed in arrays,
 passed to functions,
 returned by functions,
 and so on
+ 58

A qsort Example

/* qsort: sort v[left]…v[right] into increasing order */


void qsort(void *v[], int left, int right,
int (*comp)(void*, void*)) {
int last;
void swap(void *v[], int, int);

if (left >= right)


return;
swap(v, left, (left + right)/2);
last = left;
for (int i = left+1, i <= right; i++)
if ((*comp)(v[i], v[left]) < 0)
swap(v, ++last, i);
swap(v, left, last);
qsort(v, left, last-1, comp);
qsort(v, last+1, right, comp);
}
+ #include <stdio.h>
#include <string.h>
59

#define MAXLINES 5000

char *lineptr[MAXLINES];

int readlines(char *lineptr[], int nlines);


void writelines(char *lineptr[], int nlines);

void qsort(void *lineptr[], int left, int right,


int (*comp)(void *, void *));
int numcmp(char *, char *);

int main(int argc, char *argv[]) {


int nlines;
int numeric = 0;

if (argc > 1 && strcmp(argv[1], “-n”) == 0)


numeric = 1;
if ((nlines = readlines(lineptr, MAXLINES)) >= 0) {
qsort((void **) lineptr, 0, nlines-1,
(int (*)(void*,void*))(numeric ? numcmp : strcmp));
writelines(lineptr, nlines);
return 0;
} else
printf(“Input too big to sort\n”);
return 1;
}
+ 60

qsort Discussion

 The use of void


 If you have more than two data types to support, you may use
void type, because all types can be cast into void. Pointers as
well

 The beginning of
 Template
 Set up a computing template, that can accept different types
of variables to process, e.g.
 void swap(void *[], int, int);
 Virtual function
 Define a virtual function that dynamically determines which
function to use. However, virtual function is physically
resolved at run time and is better than the qsort example
+
Drag picture to placeholder or click ico

Not “English as
Second Language”
Drag picture to plac

C Files

6
1
+ 62

Files in C

 Not just only disk files


 I/O are handled like files too
 Devices as well
 Therefore, the term ‘handler’ is created, as the
‘mnemonic’ to handle disk files, I/O and all kinds of
devices
+ 63

Examples: stdin & stdout

 stdin
and stdout are C defined file
descriptors. stdin is the standard input from
the keyboard, and stdout is the standard
output to the monitor
 These two are equivalent, in all ways
 printf(“I am a good student\n”);
 fprintf(stdout, “I am a good student\n”);

 And these two are equivalent, too


 scanf(“%d\n”, aNum);
 fscanf(stdin, “%d\n”, aNum)
+ 64

sys/select.h
 select() allows a program to monitor multiple file descriptors, waiting until one
or more become "ready" for I/O operations (i.e., input, output or exception
throwing that do not block)
 Four macros, FD_CLR, FD_ISSET, FD_SET and FD_ZERO are provided to set/test
fd_set, the file descriptor set

#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
int select(int nfds,
fd_set *readfds, // input FD set
fd_set *writefds, // output FD set
fd_set *exceptfds, // exception FD set
struct timeval *timeout);
void FD_CLR(int fd, fd_set *set); // clear a given FD
int FD_ISSET(int fd, fd_set *set); // test if a FD is set
void FD_SET(int fd, fd_set *set); // set a given FD
void FD_ZERO(fd_set *set); // clear the FD set
+ 65

timeval

#include <sys/time.h>

struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};

int gettimeofday(struct timeval *tv,


struct timezone *tz);

int settimeofday(const struct timeval *tv,


const struct timezone *tz);

struct timezone is obsolete. Just use NULL to represent local


time
#include <stdio.h> 66
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{
fd_set rfds;
struct timeval tv;
int retval;

/* Watch stdin (fd 0) to see when it has input. */


FD_ZERO(&rfds);
FD_SET(0, &rfds);

/* Wait up to five seconds. */


tv.tv_sec = 5;
tv.tv_usec = 0;

retval = select(1, &rfds, NULL, NULL, &tv);


/* Don't rely on the value of tv now! */

if (retval == −1)
perror("select()");
else if (retval)
printf("Data is available now.\n");
/* FD_ISSET(0, &rfds) will be true. */
else
printf("No data within five seconds.\n");

return(0); // do not use exit(0);


}
+ 67

Assignment 2, Problem 2

 Pointer exercise
 Use void* malloc(size_t size); to allocate argv[1]
bytes of memory, i.e. argv[1] is the second input argument
 Use char* and a for loop, assign to the block of memory,
byte-by-byte, ‘A’ to ‘Z’ then ‘1’ to ‘9’ repeatedly, until the
memory runs out
 Then use int* and a do-while loop, to print the memory
content, in list of integers. And for each integer accessed,
subtract 1 from it
 In the integer process loop, you need to implement a guard
to prevent segmentation fault
+
End of 2nd Section
Thanks to you all!

68

You might also like