03 Intro To C

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

COMP 348: Principles of

Programming Languages

Section 3: Intro to C
Section 3 Topics

• Basic structure of a C program


– Hello world
• Trivial compilation
• cpp: The c preprocessor
• File inclusion
• The standard libraries

3-2
Basic structure

• A simple C program will look fairly similar to a


simple Java program
– main method/function
– Simple assignment statements
– Basic I/O mechanism
• Punctuation is essentially the same
– Semi colons to terminate statements
– Curly braces to designate code blocks
– Basic conditional statements and looping structures
– Function signatures consisting of return type,
function name and parameter list

3-3
Hello world

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

printf(“Hello World\n”);

return 0;
}

• The main function is the starting point of your C


application
– Automatically passed argument count and list of arguments
• main returns an int
– If return value is not provided, defaults to return 0;
– By convention, 0 is used for for valid exit, and a non-zero to
indicate some kind of error to the calling program.

3-4
Compilation
• When using an IDE like Eclipse, you often use a
“build” button (the “hammer” button in Eclipse)
• This is fine, but you should know what is
actually happening.
• C programs are compiled into object code by a
compiler.
– gcc ( GNU Compiler Collection) is probably the most
common open source version
– clang is also widely available (common on Mac)
– Other systems (Windows, Unix, BSD, etc) have their
own variations
– All should understand the same source files,
assuming they conform to a recent C language
standard.

3-5
gcc

• We will be using gcc, the default Linux


compiler and the one used in the labs
• gcc is a VERY complex program
– an online display of the gcc manual will show
hundreds of command line options.
– https://gcc.gnu.org/onlinedocs/gcc/Option-
Summary.html#Option-Summary
• Fortunately, only a handful are needed
when learning to program in C
– In fact, if you use Eclipse (or other tool), the IDE
will provide these for you

3-6
Compiler…cont’d
• The following trivial command will produce an
executable with the default name a.out
gcc hello.c

• To run the program and see the output:

a.out // or possibly ./a.out


Hello World

• Of course, we can also give our executable a


proper name, using the –o switch

gcc –o myapp hello.c


3-7
cpp: the C preprocessor

• C makes use of a pre-processor called cpp


• In short, cpp examines the source code before
the compiler
– It identifies any special cpp directives
– It transforms (re-writes) your source code into an
intermediate source file
– It passes the new source file to the compiler
• cpp is called automatically by gcc when you
compile a source file
• However, it can also be invoked as an
independent program
– By default it prints its output to the screen

cpp hello.c
3-8
cpp directives

• cpp understands a small set of about 20 directives.


– Each begins with the # symbol
• In practice, there are three forms that you will typically use as
a programmer
1. File inclusion
– #include <file>: paste a file directly into your source code.
2. Macros
– #define <content>: These are pure textual substitutions, typically
used for
• Definition of constants
• Compact form of very simple functions
3. Conditional inclusions
– For reasons that will hopefully become obvious later, we sometimes
include pre-processed content only under certain conditions
– #ifndef <label>: possibly include the content that follows
– If this case, if the label has not been defined elsewhere in the source
code, then include the code that follows this directive
– Variations for #ifdef as well

3-9
cpp directive substitution

• It is very important to understand that cpp


directives are NOT part of the C language (i.e.,
not part of the language grammar)
• In fact, if gcc was to encounter a #include
directive, it would produce an invalid syntax
error immediately
• The directives are only seen by cpp and are
then replaced by the content of the directive
• gcc NEVER knows anything about them
– It only sees the extended output created by cpp

3-10
Header files

• Let’s look at our original hello world program.


– In practice, it would typically be written as follows:
#include <stdio.h>

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

printf(“Hello World\n”);

return 0;
}

• Note the #include <stdio.h>


– This cpp directive tells the preprocessor to patch the
contents of the file stdio.h into the source file at exactly this
point.

Source file: hello.c


3-11
Standard headers

• stdio.h is an example of what is called a standard header


file.
• In short, such files are included as part of the OS/language
distribution
• These files are located in pre-defined folders that cpp and
the compiler will always search
– This is why no additional path information is included with the file
name
• Standard headers use the <file> notation
– We will see later that user-defined header files will use the “file”
notation
• Every OS/platform can define its own standard header folders
– On UNIX/Linux this will almost always at least include
– /usr/include
• On Linux, use ls /usr/include to see a list of common
header files

3-12
What is stdio.h?

• stdio.h: standard input/output


• It is the most common of all C header files
– In short, it provides the API (Application
Programming Interface) for basic IO operations,
including disk IO and screen/keyboard IO
• An overview of the API can be obtained online
or from the command line on a Linux system
as follows
– man stdio
• If you have not used Linux a lot, please get
used to the “man” pages. They are quite handy.
– Library information is in Chapter 3 of the manual.
– So you could also write “man 3 stdio”.

3-13
More header files

• /usr/include will provide a large list of header


files, besides stdio.h
• Some of these are associated with the C language
libraries. Others are associated with the operating
system itself.
• With C, there are about 30 header files, all having
their specific uses. The most common are probably
– stdio.h: input/output
– stdlib.h: general utilities including memory management
and random numbers
– string.h: character string processing
– math.h: common math functions
– time.h: basic time/date utilities
• Again, you can easily find a full list of the header
files online
3-14
Why do we need these??

• After all, Java doesn’t use header files.


• C compilation is essentially a line-by-line process,
from the top to the bottom of the source file.
• The compiler will generate an error if it encounters an
identifier that has not already been defined.
• It also wants to know what the return types are for
each function invocation
• The header files contain declarations for various
functions
– A declaration provides basic type information for the
compiler
• This is important since the compiler compiles each
source file independently
– So it does not know that this function is properly defined in
another source file

3-15
Header purpose…cont’d

• So, for example, #include <stdio.h>


includes a declaration for the printf()
function.
• This declaration gets patched into your
source code at the top of the file
– Later, you can invoke printf().
– If you see an error like “Symbol could not be
resolved”, you have probably forgotten the
associated header file.

3-16
The C standard libraries

• As with any language, a set of development


libraries are included with the C language
distribution
– A header file is associated with each individual library, in
a one-to-one fashion.
• Unlike most languages, the C library isn’t very big
• This makes sense if you consider that C was
created as a “systems” language that would
support Unix.
– Large SDKs (software development kit) weren’t necessary
at that time since there wasn’t a lot of “application”
programming.
– That said, C has been around for a long time so there
are a lot of 3rd party C libs available.
• For example, GTK+ is a large C library that can be used to
build sophisticated graphical user interfaces (GUIs)

3-17
Printing to the screen

• Before we can look at more useful programs, we


need to be able to display results conveniently.
• C provides the printf() function for this
purpose (the “f” is for format).
• Unlike Java (and other languages), you have to do
a little more manual formatting
– Specifically, you must embed type substitution
characters in the print string.
– The values of specific variables are then substituted in
the text string before being displayed
• The stdio.h prototype for printf() looks like this:
– extern int printf (const char *__restrict __format, ...);
– Note that the “…” is a mechanism that supports variable length
argument lists

3-18
printf()

• The basic form use of printf() is as follows:


printf(formatting string, variable list);

• The % sign represents the substitution character


• Examples include:

printf(“hello world”); // hello world

printf(“I am %d”, age); // I am 103

printf(“Items: %d, value: %f”, count, sum); // Items: 6, value: 34.5

3-19
printf output specifiers

• Each valid C data type has its own output specifier.


• There are quite a few of these but the main ones
include:
– d or i: decimal integer
– f: floating point value
– s: character string
– c: individual character
– p: pointer address value
• There are also flags for additional things like
– left/right justification
– Leading zeros
– Minimum number of digits (padded with blanks, if necessary)
– Numeric precision (for “f”, number of digits after the decimal)
• A list of all of the specifiers and flags are available
online

3-20
Printing error messages

• While it is possible to use printf to display error or


warning messages, you should NOT do this.
• Instead, use fprintf(stderr, message, variable_list)
• Why?
– printf attempts to increase the efficiency of your I/O
– Specifically, it uses a buffered file stream
– The OS is only asked to do IO when the buffer is full
– This is good, but small messages can sit in the buffer for a
long time
• Errors and warnings should print immediately.
– stderr is unbuffered so the message goes to the OS as
soon as fprintf is called
– The OS still decides when to write to the screen, but this is
usually almost immediately.
– Note that Java and C++ have similar error streams. You
should use them as well.

3-21
Summary

• This section has introduced the most basic


features of C
– Design of simple programs
– Basic syntax
• In the following sections, we will continue
to add features in order to produce fully
functional C programs.
– As we do, the differences relative to Java will
become more apparent.

Source file: helloplus.c


3-22

You might also like