tutorial 2: compiling and running c++ source codeamer/teach/coen243/unixlabs/lab2.pdf · tutorial...

6
Tutorial 2: Compiling and Running C++ Source Code 1. Log in to your UNIX account as you did during the first tutorial. 2. Click on the desktop with the left mouse button and consider the menu that appears before you. 3. Select utilities. 4. Select Nedit. As I ’m sure you remember, this is the text editor with which you will be writing your C++ code. 5. Type the following: #include <iostream> using namespace std; int main() { cout << “Hello World!”; cout << endl; return 0; } 6. Now click on “File” at the top of the Nedit window. 7. Select “Save As”. The directory in which your file should be saved appears by default. As before, you do not need to modify this directory. In the space provided, name your file hello.cpp Congratulations! You have just written your first C++ program; now to compile. 8. Go back to your xterm window and type: g++ -pedantic -o hello hello.cpp 9. Press enter. (In case it is not clear, there is a space between “g++” and “-o”, and the “-o” is the letter o, not a zero.) This will compile the program you have just written using the g++ compiler. Using -pedantic makes the compiler check your code against the C++ standard. The filename after the -o indicates the name of the executable file (i.e. runnable file) you would like created after compiling your source code (hello.cpp) successfully. If you don’t specifiy the –o hello, a file called a.out will be created automatically. If the compilation was successful, you will simply get your command prompt again (if you see some other messages displayed, they are errors – see item 11).

Upload: nguyentuyen

Post on 12-May-2018

217 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Tutorial 2: Compiling and Running C++ Source Codeamer/teach/coen243/UnixLabs/Lab2.pdf · Tutorial 2: Compiling and Running C++ Source Code 1. Log in to your UNIX account as you did

Tutorial 2: Compiling and Running C++ Source Code

1. Log in to your UNIX account as you did during the first tutorial. 2. Click on the desktop with the left mouse button and consider the menu

that appears before you. 3. Select utilities. 4. Select Nedit. As I’m sure you remember, this is the text editor with

which you will be writing your C++ code. 5. Type the following:

#include <iostream> using namespace std; int main() {

cout << “Hello World!”; cout << endl; return 0;

}

6. Now click on “File” at the top of the Nedit window. 7. Select “Save As”. The directory in which your file should be saved

appears by default. As before, you do not need to modify this directory. In the space provided, name your file hello.cpp Congratulations! You have just written your first C++ program; now to compile.

8. Go back to your xterm window and type:

g++ -pedantic -o hello hello.cpp

9. Press enter. (In case it is not clear, there is a space between “g++”

and “-o”, and the “-o” is the letter o, not a zero.) This will compile the program you have just written using the g++ compiler. Using −pedantic makes the compiler check your code against the C++ standard. The filename after the -o indicates the name of the executable file (i.e. runnable file) you would like created after compiling your source code (hello.cpp) successfully. If you don’t specifiy the –o hello, a file called a.out will be created automatically.

If the compilation was successful, you will simply get your command prompt again (if you see some other messages displayed, they are errors – see item 11).

Page 2: Tutorial 2: Compiling and Running C++ Source Codeamer/teach/coen243/UnixLabs/Lab2.pdf · Tutorial 2: Compiling and Running C++ Source Code 1. Log in to your UNIX account as you did

10. Now that your program is compiled, you need only run it in order to view the results. To do this type the following in the xterm window and press enter:

./hello

11. If the compiler found errors in your code, it will display them. For example, if you forget an ending quotation mark in your output string (i..e cout << “Hello World!;), you will receive the following error after compiling:

[dea] [/home/a_gombar] > g++ -pedantic -o hello hello.cpp hello.cpp:6: warning: string constant runs past end of line hello.cpp:6: unterminated string or character constant hello.cpp:6: possible real start of unterminated constant

Note that your prompt will differ from [dea] [/home/a_gombar] > You should recreate this error to see how errors are displayed with g++. Don’t forget to save your changes before compiling!!

Shortcut: Press Control-S in Nedit to save your changes.

Don’t forget to save any modifications to your source code before recompiling, otherwise only your last changes will be compiled by g++. An easy way to see if you have saved your file in nedit is to look at the filename displayed at the top left corner of the Nedit window. If the word (modified) is displayed after the filename, then you have modified the file and not saved it yet. If you save the file (FileàSave or Ctrl-S) you will see that (modified) will be gone.

12. The line number that the error was detected is also displayed. In the above case, the error was found on line 6: hello.cp:6: It would be nice to view line numbers in Nedit, which can be done as follows:

i. In Nedit, go to PreferencesàDefault Settings and click on Statistics Line.

ii. Exit the Nedit program (FileàExit). iii. A message box is displayed stating “Default Preferences have

changed”. Click on Save to accept the changes. iv. Restart Nedit. There should be an information line just below

the top menu that displays the line and column position for the current cursor location.

Page 3: Tutorial 2: Compiling and Running C++ Source Codeamer/teach/coen243/UnixLabs/Lab2.pdf · Tutorial 2: Compiling and Running C++ Source Code 1. Log in to your UNIX account as you did

Now let’s try prompting the user for an input and then displaying what they entered. We’re also going to add some comments to our program because we want to develop good programming habits.

1. From Nedit, click “File” and select “New” from the drop down menu.

Then type the following:

//input.cpp Prompts the user for input #include <iostream> // required for cin/cout using namespace std; int main() //start of main function {

float input; //input: float variable //input by user

//Get the input cout << "Enter a float number: "; cin >> input; //Display the input cout << "You entered " << input << endl; return 0;

}

Save the file as input.cpp. Return to xterm window, compile and run.

g++ -pedantic -o input input.cpp ./input

When it runs, notice that you are prompted to enter a number. Type 2.9 and press enter. Notice that 2.9 is the output. If error messages are displayed then you will need to debug your source code (i.e. check for errors). Do not panic, this is a normal part of the programming process. You will often spend more time debugging then you do writing the actual program and that’s okay.

Page 4: Tutorial 2: Compiling and Running C++ Source Codeamer/teach/coen243/UnixLabs/Lab2.pdf · Tutorial 2: Compiling and Running C++ Source Code 1. Log in to your UNIX account as you did

Some easy debugging fixes.

1. Check your brackets and parentheses. Make sure that every bracket/parentheses opened is also closed {} ( )

2. Quotation marks. Like brackets, what is opened must be closed. 3. Make sure that every line of code ( not comments // ) ends with a

semicolon ; 4. Make sure that comment lines begin with TWO forward slashes // 5. Make sure that when you use cin >> and cout << properly, so for

example, cin << will cause an error because the << is facing the wrong way (>> is the stream extraction operator (cin) and << is the stream insertion operator (cout)).

6. It may happen that when you look at the line number where the compiler found an error, you don’t see any mistakes. Sometimes the error is actually just above the line number displayed, so look a few lines above for a mistake. Many times a missing semicolon is the culprit!

7. Sometimes you will get overwhelmed by very many errors. But in certain situations correcting one error can correct a cascade of other related errors.

8. Build your program in a piecewise fashion. In other words, build a basic program that can run (i.e. just a main() function). Then add functionality by coding a small component of your complete program. Compile and test what you have so far and once you’re satisfied with it, add another component. This is also a very good method when you doing the online exam. If you try to complete most of your program in one sitting, you will be inundated with errors!! Also, an error in one part of your program might create errors in other parts.

Page 5: Tutorial 2: Compiling and Running C++ Source Codeamer/teach/coen243/UnixLabs/Lab2.pdf · Tutorial 2: Compiling and Running C++ Source Code 1. Log in to your UNIX account as you did

As an exercise, compile and run the following program that includes some errors. Type and compile the file as is so you get a feel for the type of error messages you can receive. Then correct the errors and recompile until the program is running correctly.

Shortcut: instead of retyping the code, select it with your mouse and then paste it into nedit using the middle mouse button

The program requires the user to enter a number in pounds and it will be converted to kilograms. Test your program by inputting 10. Your answer should be 22.

// Program converts pounds to kilograms #include <iostreaam> using namespace std; int main() { const float LBSTOKGS = 2.2 // pounds in 1 kg float numPounds, numKilograms; // Request weight (lbs) from user cout << "Enter weight in pounds “

<< “to convert to kilograms: "; cin << numkilograms; // convert pounds to kilograms numKilograms = numPounds * LBSTOKGS; // Output converted value cout << "The weight in kilograms is " << numKilograms; cout << endl; return 0; }

Note the good use of spacing and indenting to make the program clear to read. To help you along, the above program contains 5 errors: 4 syntax errors and 1 logic error. A syntax error is a mistake in using the C++ language (e.g. writing ciin instead of cin), whereas a logic error is when your program runs, but does not work as expected. Logic errors will be discovered once you fix any syntax

Page 6: Tutorial 2: Compiling and Running C++ Source Codeamer/teach/coen243/UnixLabs/Lab2.pdf · Tutorial 2: Compiling and Running C++ Source Code 1. Log in to your UNIX account as you did

errors and your program is able to run. For instance, a logic error would be subtracting two numbers when you meant to divide them. In this case your program would run, but you would have an incorrect answer.

Close your xterm window by typing exit in the xterm window and press enter.

Close Nedit. Quit your session. Good Work! See you next week!