A couple of lines to print “Hello world”:
#include <stdio.h>
main()
{
printf("hello world\n");
}
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
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:
-std=c90
specifies the ANSI C standard (also called ISO or standard C)-std=c17
specifies the C standard published in 2018For other options see the manual page with man gcc
.
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 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);
}
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:
-2^15
to 2^15 - 1
(-32768 to 32767)The short integer (short
) variable type seems to be 16 bits (2 bytes).
The long integer (long
) type also seems to be 16 bits (2 bytes). Investigate why this is.
Comments explain what a C program is doing. They are ignored by the compiler.
There are two ways to add comments:
//
/*
and end with */