Compiling a “Hello world” program

A couple of lines to print “Hello world”:

#include <stdio.h>

main()
{
  printf("hello world\n");
}

Compiling on Linux

If the above source code is saved in 1_hello.c:

ls
#> 1_hello.c

It can be compiled to an executable file using the GNU Compiler Collection using the gcc command.

Pass the -o file option to give a name for the outputted executable file. For example gcc -o hello 1_hello.c is telling GCC to compile the file 1_hello.c and output it is hello.

After running the command you now have a new file:

ls
#> 1_hello.c  hello

Run the exectubable file:

./hello
#> hello world

Other gcc options

There are other options that can be passed to gcc along with the name of the outputted filed (-o).

For example the -std= option can specify the C standard to use in compilation:

For other options see the manual page with man gcc.

Compiling on Windows

Explanation

A C program consists of functions and variables. Functions contain statements that specify the operations to be done and variables to store values used during the computation.

In the the simple “Hello world” program the main() function is special. All C programs must have a main() function as this is where execution will begin.

The #include <stdio.h> statement is saying the standard C input/output library is needed. It is needed for the printf() function which comes from the standard input/output library.

A sequence of characters in double quotes like “hello world\n” is a called a character string or a string constant.

Variables

Variables and their types must be declared before they are used. Variables are assigned to with the equals sign. Variables that have been assigned to can be used in later statements.

#include <stdio.h>

main()
{
  /* a simple program demonstrating variable:
    - declaration
    - assignment
    - use */

  // declarating variables
  int integerVariable;
  char characterVariable;

  // assigning to variables
  integerVariable = 1;
  characterVariable = 'C';

  // using variables
  printf("%c is number %i\n", characterVariable, integerVariable);
}

Variable data types

Integers

The int variable type means integer. As of C standard (to figure out) an integer (int) is at least 16 bits (2 bytes). 32 bit (4 byte) integers are also common. You can investigate this on the system you are working on with sizeof().

The length of an integer determines the range of integers it can actually store:

Short integers

The short integer (short) variable type seems to be 16 bits (2 bytes).

Long integers

The long integer (long) type also seems to be 16 bits (2 bytes). Investigate why this is.

Floating point numbers

Double precision floating point numbers

Character

Comments

Comments explain what a C program is doing. They are ignored by the compiler.

There are two ways to add comments: