Introduction to C

module = Module(
    code="ELEE1147",
    name="Programming for Engineers",
    credits=15,
    module_leader="Seb Blair BEng(H) PGCAP MIET MIHEEM FHEA"
)
Introduction To C

Why C?

Developed by Denis Ritchie [1941-2011] in 1972

  • Low-level access to memory
  • A simple set of keywords
  • A clean style
  • Suitable for system programming:
    • operating systems
    • compiler development
  • Procedural and structured programming
  • Portable across various platforms
  • Combines low-level hardware control and high-level language convenience
#include <stdio.h>

int main(){

  printf("Hello World!\n");

  printf("Goodbye World!");

  return 0;
}
Introduction To C > Why C?
Introduction To C > Why C?

C God's programming language*

*Shreiner D. 2010. OpenGL programming guide : the official guide to learning OpenGL, versions 3.0 and 3.1. 7th ed. Upper Saddle River, Nj: Addison-Wesley.

Introduction To C

First Program in C

$ mkdir Learning_C && cd Learning_C
$ mkdir Helloworld && cd Helloworld
$ touch helloworld.c
$ <nano/vim/vi> helloworld.c
Introduction To C > First Program in C
  • Single line comments
// library or header file that contains  standard input/output operatioins

#include <stdio.h>

/* 
  main() function every C program must have a main, 
  it has a returnable 'int' this is for exit codes
*/
int main(void) // void means no input argument
{
    printf("Hello World!\n");
    printf("Goodbye World!\n");
    return 0; // return exit code 0, no error
}
Introduction To C > First Program in C
  • directive, tells the preprocessor to include the contents of a specified file.
// library or header file that contains  standard input/output operatioins

#include <stdio.h>

/* 
  main() function every C program must have a main, 
  it has a returnable 'int' this is for exit codes
*/
int main(void) // void means no input argument
{
    printf("Hello World!\n");
    printf("Goodbye World!\n");
    return 0; // return exit code 0, no error
}
Introduction To C > First Program in C
  • Multi-line comments
// library or header file that contains  standard input/output operatioins

#include <stdio.h>

/* 
  main() function every C program must have a main, 
  it has a returnable 'int' this is for exit codes
*/
int main(void) // void means no input argument
{
    printf("Hello World!\n");
    printf("Goodbye World!\n");
    return 0; // return exit code 0, no error
}
Introduction To C > First Program in C
  • All C programs need a main() function as it's entry point
// library or header file that contains  standard input/output operatioins

#include <stdio.h>

/* 
  main() function every C program must have a main, 
  it has a returnable 'int' this is for exit codes
*/
int main(void) // void means no input argument
{
    printf("Hello World!\n");
    printf("Goodbye World!\n");
    return 0; // return exit code 0, no error
}
Introduction To C > First Program in C
  • Body of the code that is executed, wrapped in braces {}
// library or header file that contains  standard input/output operatioins

#include <stdio.h>

/* 
  main() function every C program must have a main, 
  it has a returnable 'int' this is for exit codes
*/
int main(void) // void means no input argument
{
    printf("Hello World!\n");
    printf("Goodbye World!\n");
    return 0; // return exit code 0, no error
}
Introduction To C > First Program in C

Compile the code

We are going to use gcc compiler to compile our c code;

$ gcc helloworld.c -o helloworld.exe
  • first argument is the source file[s], helloworld.c
  • -o means output file, helloworld.exe
  • The file extension in linux can be left blank or called whatever you want.

drop-shdaow

Introduction To C > First Program in C

Execute the code

  • As we are using a terminal, we must prepend the newley created file with ./.

    • The . denotes the current directory.
  • Since we want to run a file in our current directory which is not our $PATH

    • You need the ./ bit to tell the shell where the executable is.

Output:

$ ./helloworld.exe
Hello World!
Goodbye World!
Introduction To C > First Program in C

Header Files

These files contain all scaffolding code that your main() will use as we do not want to overpopulate with excessive lines of code for readability.

Computers used to be too slow to compile a whole program in one single mega-blob where all the functions and types were visible.

To solve this, programs are split into c/h files which are each individually compiled into a machine code file (the ‘object’ file), and then linked together into an exe or dll.

Introduction To C > First Program in C > Header Files
  • Create a new header file:

    $ touch usefulfunctions.h
    $ <nano/vim/vi> usefulfunctions.h
    
  • usefulfunctions.h

    #ifndef USEFULFUNCTIONS_H_   /* Include guard */
    #define USEFULFUNCTIONS_H_
    
    int sqr(int x);  /* An example function declaration */
    
    #endif // USEFULFUNCTIONS_H_
    
  • Create a new source file:

    $ touch usefulfunctions.c
    $ <nano/vim/vi> usefulfunctions.c
    
  • usefulfunctions.c

    #include "usefulfunctions.h"  /* Include the header (not strictly necessary here) */
    
    int sqr(int x)    /* Function definition */
    {
        return x * x;
    }
    
Introduction To C > First Program in C > Header Files

Revist helloworld.c

We are modifiying the code to use our custom library:

#include <stdio.h> /* searches system header file directories */
#include "usefulfunctions.h" /* notice "" searches current directory */

int main(void) /* void means no input argument */
{
    printf("Hello World\n!");  /* using standard ouput function to printf()*/
    printf("%d\n",sqr(255));
    printf("Goodbye World!\n");

    return 0; /* return exit code 0, no error */
}

Introduction To C > First Program in C > Header Files

Compile and run

We need to source all files needed to build our modified program.

Remember the header file points to the function in the usefulfunctions.c file.

$ gcc helloworld.c usefulfunctions.c -o helloworld.out

Output:

$ ./helloworld.out
Hello World!
65025
Goodbye World!
Introduction To C > First Program in C > Header Files

Standard Input and Output

  • stdio.h is a large file that contains many function declarations, in fact there are 827 lines of code for this header file alone.

    /* Define ISO C stdio on top of C++ iostreams.
    Copyright (C) 1991-2024 Free Software Foundation, Inc.
    Copyright The GNU Toolchain Authors.
    This file is part of the GNU C Library.
    ...
    */
    #ifndef _STDIO_H
    #define _STDIO_H	1
    ...
    /* Write formatted output to stdout.
    This function is a possible cancellation point and therefore not
    marked with __THROW.  */
    extern int printf (const char *__restrict __format, ...);
    
Introduction To C

Primitive Data Types

Introduction To C > Primitive Data Types

Primitive Data Types

C has several data types and all variables must have a data type

Data Type Size (Bytes) Range Format Specifier
(unsigned)char at least 1 to or to %c
(unsigned)short at least 2 to , to %h
(unsigned)int at least 2 to to %u,%d
long least 4 to %l, %ll, %lld, %lli
unsigned long at least 4 to %lu,%llu
float at least 2 to %f
(unsigned)double at least 8 to %lf
long double at least 10 to %Lf
Introduction To C

C Advanced Features

  • Pointers and addressing, int*, &var1 (more about this later)
  • struct
    • Allows to combine data items of different kinds
    • struct Books { char title[50]; char author[50]; int book_id;} book
  • enum
    • It consists of constant integrals or integers that are given names by a user.
    • enum enum_name{int_const1, int_const2, int_const3, …. int_constN};
  • union
    • allows to store different data types in the same memory location
    • union Data { int i; float f; char str[20];} data;
Introduction To C

Embedded C

ANSEL  = 0;      // Configure AN pins as digital I/O
ANSELH = 0;
C1ON_bit = 0;    // Disable comparators
C2ON_bit = 0;
//         76543210
TRISC  = 0b10000000;   // PORTC is input
UART1_Init(9600); // Initialize UART PROTO

...

ANSELA  = 0;      // Configure AN pins as digital I/O
ANSELB  = 0;
ANSELC  = 0;
TRISB = 0;
Introduction To C

Objective-C

#import "MyClass.h"
 
@implementation MyClass
- (id)initWithString:(NSString *)aName
{
    // code goes here
}
 
+ (MyClass *)myClassWithString:(NSString *)aName
{
    // code goes here
}
@end
Introduction To C

Compilation

Throughout this session we have been using gcc or `the GNU Compiler Collection'. The GNU is a recursive acronym: ‘GNU’s Not Unix!'

Supports:

  • C,
  • embedded-C ,
  • Objective-C,
  • C++,
  • Fortran,
  • Ada,
  • Go,
  • and D
  • Example C code
int square(int num) {
    return num * num;
}
  • Example assembley code from gcc
square:
 push   %rbp
 mov    %rsp,%rbp
 mov    %edi,-0x4(%rbp)
 mov    -0x4(%rbp),%eax
 imul   %eax,%eax
 pop    %rbp
 ret
Introduction To C

Command Line Arguments

$ mkdir arguments && cd arguments
$ touch arguments.c
$ vim arguments.c
Introduction To C > Command Line Arguments
  • main() can now take an integer as an argument.
#include <stdio.h>

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

   printf("Program name %s\n", argv[0]);
 
   if( argc == 2 ) {
      printf("The argument supplied is %s\n", argv[1]);
   }
   else if( argc > 2 ) {
      printf("Too many arguments supplied.\n");
   }
   else {
      printf("One argument expected.\n");
   }
   return 0;
}
Introduction To C > Command Line Arguments
  • argv[0] this is an array, at index 0 is the current programs file name... always.
#include <stdio.h>

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

   printf("Program name %s\n", argv[0]);
 
   if( argc == 2 ) {
      printf("The argument supplied is %s\n", argv[1]);
   }
   else if( argc > 2 ) {
      printf("Too many arguments supplied.\n");
   }
   else {
      printf("One argument expected.\n");
   }
   return 0;
}
Introduction To C > Command Line Arguments
  • if( argc == 2 ) checks to see if the number of arguments supplied is 2, (program name is 1)
#include <stdio.h>

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

   printf("Program name %s\n", argv[0]);
 
   if( argc == 2 ) {
      printf("The argument supplied is %s\n", argv[1]);
   }
   else if( argc > 2 ) {
      printf("Too many arguments supplied.\n");
   }
   else {
      printf("One argument expected.\n");
   }
   return 0;
}
Introduction To C > Command Line Arguments
  • ...%s\n", argv[1]) gets the argument you supplied and then formats it as string to the terminal
#include <stdio.h>

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

   printf("Program name %s\n", argv[0]);
 
   if( argc == 2 ) {
      printf("The argument supplied is %s\n", argv[1]);
   }
   else if( argc > 2 ) {
      printf("Too many arguments supplied.\n");
   }
   else {
      printf("One argument expected.\n");
   }
   return 0;
}
Introduction To C > Command Line Arguments
  • else if( argc > 2 ) if the first if is false, then check to see if you have supplied 2 arguments
#include <stdio.h>

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

   printf("Program name %s\n", argv[0]);
 
   if( argc == 2 ) {
      printf("The argument supplied is %s\n", argv[1]);
   }
   else if( argc > 2 ) {
      printf("Too many arguments supplied.\n");
   }
   else {
      printf("One argument expected.\n");
   }
   return 0;
}
Introduction To C > Command Line Arguments
  • else if you have not supplied an argument
#include <stdio.h>

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

   printf("Program name %s\n", argv[0]);
 
   if( argc == 2 ) {
      printf("The argument supplied is %s\n", argv[1]);
   }
   else if( argc > 2 ) {
      printf("Too many arguments supplied.\n");
   }
   else {
      printf("One argument expected.\n");
   }
   return 0;
}