4CCE1PHC
1 Introduction
Hello World
September 27, 2021
This lab introduces you to C programming. It aims to (i) introduce you to the resources available to read up on features of the C language, (ii) introduce you to the use of a command line shell to interact with the computer through a terminal, and (iii) familiarise you with the tool chain consisting of a text editor and a C-compiler.
At the end of the lab, you should be able to:
• Write simple C programs.
• Compile and run C programs from the command line. • Interpret error messages from the compiler.
Before starting work you should read through this document and complete the preparatory tasks detailed in §2.
2 Preparation
Materials
Make sure you have everything you need to complete this lab.
Ensure that you have the following software installed on your computer: (i) a terminal program (e.g., xterm or similar on Linux/Mac OS, cygwin on Windows), (ii) a text editor (e.g., gedit or similar on Linux/Mac OS, notepad++ on Windows), (iii) the GNU compiler collection (i.e., gcc).
Self-study
Part 1
Read §3 below, read up on any new material (in textbooks and/or online) that you need to, to accomplish the tasks. Remember to make notes of where you got the information, so that you can quickly go there again if something does not work as expected.
Read up on how to use variables in C, either in a textbook or the C Wikibook section on variables1. Then write down a declaration for a variable. You should know what its type is, what its name is, and what its value is.
An example variable declaration is:
1 int x = 123;
Here, the variable is of type int, its name is x and the value is 123.
1 https://en.wikibooks.org/wiki/C_Programming/Variables
Dr 1 © 2020
Deparment of Engineering King’s College London
4CCE1PHC
/* hello_world.c
/* A famous test for the C build process. */
1
2
3
4
5
6
7
8 9}
#include
int main(void) { printf(“Hello␣World\n”); return 0;
Listing 1: The closing */ in line 1 is missing. /* hello_world.c */
/* A famous test for the C build process. */
1
2
3
4
5
6
7
8 9}
#include
int main(void) { printf(“Hello␣World\n”); return 0;
Part 2
Listing 2: The name of the library in line 4 has been changed.
Consider the three variations of the “Hello World” code in Listing 1, Listing 2 and Listing 3.
Complete the table below with what you expect to happen when these variants are compiled. You are not expected to get these right, but you should be able to justify why you answered in the way you did.
Listing 1
Listing 2
Listing 3
x
No error message
An error from the preprocessor An error from the compiler
An error from the linker
x
x
In Listing 1, the comment is closed by the final */ on line 2, so the opening /* on that line is treated as part of the comment. This means that the code has no error (but, stylistically, this should be avoided!)
In Listing 2, there is no such library as mystdio.h, so the preprocessor will raise an error when trying to
/* hello_world.c */
/* A famous test for the C build process. */
int main(void) { myprintf(“Hello␣World\n”); return 0;
Listing 3: The name of the function called in line 7 has been changed.
Dr 2 © 2020
1
2
3
4
5
6
7
8 9}
#include
Deparment of Engineering King’s College London
4CCE1PHC
gather together all the files needed by the compiler.
In Listing 3, the compiler will assume that the function myprintf is defined in the stdio.h, however, as there is no such function in the library, the error will be raised when the linker is used to try to incorporate the function into the executable.
3 Laboratory Work
3.1 Set Up
To set up your work environment, take the following steps:
1. Open a terminal. The way to do this depends on whether you are using Linux, Mac OS, or Windows.
• In Ubuntu 20.04 LTS, simply right-click the mouse on the desktop background and select “Open
Terminal” from the menu that appears.
• In Windows, download and install Cygwin.2 Once the installation is complete, use the start
menu to open the Cygwin terminal.
• In Mac OS, click the Launchpad in the Dock, search for ”Terminal” and then press enter.
Alternatively, open the /Applications/Utilities folder in the Finder and double-click ”Terminal”. Once you have completed these steps, the window that opens is a command line interface. That is, you type commands directly in this window. This is where you will compile and run your code.
2. Create a new folder to store your work in. You can do this using the terminal through the following steps:
(a) Move to your home folder by typing the command cd into the terminal and hitting the return key.
(b) Create a folder by typing the command mkdir folder_name into the terminal and hitting the return key. Name your folder in a suitable way for this lab, e.g., 4CCE1PHC lab1.
Hint: Do not use any spaces in your folder names or your file names!
(c) Move into the new folder by typing the command cd folder_name (e.g., cd 4CCE1PHC lab1) into the terminal and hitting the return key.
Hint: The terminal remembers previous commands and you can use the up-arrow cursor key to bring up a previously entered command line. You can also use the Tab key to let the command line attempt to complete what your typing. (Try this out, it is very convenient.)
3. Download the file hello_world.c from KEATS.
Use a browser (e.g., Firefox or Chrome), and use the “Save As” option to save the file into the new folder you just created. In the terminal you can type ls (which stands for “list”) to show the files in your folder. It should now show the hello_world.c file.
4. Open the file in a text editor. You can use any plain text editor, such as gedit or notepad++. To start the editor from the terminal window, simply enter the name of the editor, followed by & in the terminal window. For example, if you are using gedit, enter gedit&. Alternatively, select the editor from the Applications/Programming menu. The text editor is where you will view and edit your C code. Use the editor to open the file you downloaded in step 3. You should see the code from Listing 4 displayed.
Hint: You may find it helpful to resize the terminal window so that it takes up about half of your screen, with the editor taking up the other half.
3.2 Hello World
You are now ready to compile and run your first C program.
1. To compile the program, enter the following command in the terminal and hit return: 2 https://www.cygwin.com
Dr 3 Deparment of Engineering © 2020 King’s College London
4CCE1PHC
1 /* hello_world.c */
2 /* A famous test for the C build process. */
3
4 #include
6 #define SUCCESS 0
7
8 int main() {
9 10
11 }
printf(“Hello␣World\n”); return SUCCESS;
Listing 4: hello_world.c.
gcc hello_world.c -o hello_world
This will run the gcc compiler,3 tell it to compile the file hello_world.c and to write the output of the compilation to a file named hello_world.
Hint: On the command line, the first word is always the command to be called, subsequent words are command line arguments that will be supplied as input to the command, or command line options that change how the command will act. The latter start with a dash (-). So here, hello_world.c is an argument, and -o (“output”) is an option, that is followed by an argument for the option, the hello_world.
Think: Why was there a warning above (§3.1, step 2b) not to place spaces in file names or folder names? Because on the command line, spaces are used to separate the instructions to the computer, so spaces in file names will confuse it!
2. Use the ls command to see what you find in your folder. The compiler has produced an executable file from the source code.4
Hint: Be very careful that you never specify the filename of your source code as the name where the compiler output should be written to–otherwise the compiler will overwrite it without warning! While you develop a program it is a good idea to make frequent backup copies. You can use the cp (“copy”) command to make bakups like this:
cp hello_world.c hello_world_bak001.c
3. You can now run this program, by typing its file name in the terminal:
./hello_world
It should print its message on the terminal. Note how your hello_world.c program now acts like a new command named hello_world. In fact, many of the command line commands are just C programs with the corresponding name. One can easily add new commands by writing the required C programs.
4. Now modify the hello_world.c program to produce versions equivalent to the three listings in §2 above. Compile after each change and observe the messages from the compiler. Note what errors are raised and write some comments on how these error messages correspond to the changes you made.
Think: How do you recognise which part of the build phase (preprocessor, compiler, linker) raised the error? Do your observations agree with your expectations from the preparation? Usually errors
3The gcc stands for GNU Compiler Collection, because it provides front-ends for several languages and back-ends for many processor architectures.
4On Windows, the ending .exe is added to indicate that it is executable.
Dr 4 Deparment of Engineering © 2020 King’s College London
4CCE1PHC
1 /* hello_x.c */
2 /* Hello with text string. */
3
4 #include
5
6 #define SUCCESS 0
7
8 char name[]=”human”; 9
10 int main() {
11
12
13 }
printf(“Hello␣%s!\n”, name ); return SUCCESS;
Listing 5: hello_x.c.
at the preprocessor/compiler stage end with ‘compilation terminated’. Often it also gives you a line number. Usually errors at the linker stage end with the message ‘ld returned 1 exit status’. The compiler might issue a warning. In both cases, usually no executable file is created.
5. Modify the hello_world.c program by removing the closing comment symbols */ from the second line rather than the first line and compile it.
Think: How does this change the response of the compiler? The compiler exits with the error ‘unterminated comment’. In effect the comment never ends, no code can be compiled.
3.3 Printing Text Strings
The program hello_world.c does not do anything very useful as it always prints the same message. To make it more flexible we can use a variable to store all or part of the message that it prints. This will allow us to print different messages.
1. Download hello_x.c from KEATS, save it in your folder and open it with your text editor. In the program you find a variable declaration with initialisation—in this case, a text string that is an array of characters. Observe how the value of the variable is included in the output of the program.
2. Use the text editor and add your own variable declaration from the preparation to the code. Then change the printf() statement, such that it prints the value of your variable.
Hint: Depending on the type of variable you wrote down in the preparation you will need a suitable format specifier in the first argument to the printf() function. In the example given, the format specifier %s specifies that a string argument will follow. See Table 1 for more format specifiers. For the example in §2, the following code could be used:
1 2 3 4 5 6 7 8 9
10 11
/* Hello with my variable. */
#include
#define SUCCESS 0
int main() {
int x = 123; printf(“x␣=␣%d\n”, x); return SUCCESS;
}
Dr 5 © 2020
Deparment of Engineering King’s College London
4CCE1PHC
1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17
/* hello_input.c */ /* Ask for input. */
#include
#define NAME_BUFFSIZE 100 char name[NAME_BUFFSIZE];
int main() { printf(“What␣is␣your␣name␣?␣”); scanf(“%s”,name); printf(“Hello␣%s!\n”,name); return SUCCESS;
}
3.
Listing 6: hello_input.c.
Note that, as the example variable is an int the %d format specifier causes its value to be printed in decimal format.
After you have successfully printed out the value of your variable, investigate what happens if the variable type and the format specifier do not match. Keep notes of the results of your experiments.
Type
int
int
float or double float or double char
Format Specifier
%d %x %f %e %c
Output
decimal value hexadecimal value fixpoint notation exponential notation
4 4.1
Table 1: Format specifiers.
Optional Additional Work User Input
Our program can be made even more useful if we allow it to take input to a user. In this section, you will learn how to do this.
1. Download hello_input.c from KEATS, save it in your folder and open it with your text editor.
2. Compile the program and test it.
Think: In line 10 memory space is reserved for the user input. What do you think will happen if the
input is larger than the reserved space?
3. Change line 8 to make the buffer smaller and test what happens with a long input. The following code is an example:
1 #define NAME_BUFFSIZE 10
When you run this, it seems to work fine. However, if you put in more than ten characters you are
actually overflowing the allocated memory, which means the program will write in an uncontrolled
Dr 6 Deparment of Engineering © 2020 King’s College London
4CCE1PHC
way to adjacent memory. This should be avoided as it can cause serious problems! Fun fact: Many
security attacks (“buffer-overflow attack”) exploit this kind of bug!
4. Modify the code such that you can read a value for the variable you declared in the preparation for the lab. Read the value from the user input and print it out to confirm it works as intended.
Think: What happens if the user input does not match the type of your variable?
Dr 7 Deparment of Engineering © 2020 King’s College London