Structure of programming

Fundamental structure of C programming

A simple structure of C programming is as follows.

#include <stdio.h>

int main(void) {


    return (0);

}

Each line has a meaning explained as follows.

#include <stdio.h>  <- Including a header file related to standard IO

int main(void) { <- Beginning of main function


    return (0);     <- Return result of the function

}  <- End of main function

Fundamental rules

Compilation and execution

Write below source code, and save it as "hello.c".

#include <stdio.h>

int main(void) {

    printf("Hello\n");

    return (0);

}

printf(   ) is a function to show characters and numerical values of variables.

In order to execute a source code programmed in C language, it must be comiled and executable file must be created. How to compile is as follows.

$ cc hello.c
or
$ gcc hello.c

If you fail in compilation, message such as below will be shown. If so, you have to check your source code including typo (typing error), which is one of major causes for comiliation error. In the below case, the cause was to forget ; after a function of "printf".

$ gcc hello.c
hello.c: In function `main':
hello.c:7: parse error before `return'

If you read the above error message carefully, it says that "parse error before `return'". It means you had better check especially before "return".

After you correct errors, try compilation again. If it succeeds, executable file will be produced. You can check whether it was produced by typing UNIX command, "ls"

$ ls
a.out   hello.c

The file "a.out" is an executable file. In order to execute it, type as follows. Then, you'll get a message, "Hello".

$ ./a.out
Hello

When you want to name an executable file as a different name, you can name in the below manner. In the below case, the executable file is named as "hello".

$ cc -o hello hello.c
or
$ gcc -o hello hello.c

In order to execute it, type as follows.

% ./hello
Exercise: Type "hello.c" written in the above, compile and execute it. Check whether it runs properly.

Lessons for C programming
Junichi Susaki, Kyoto University