C++ Tutorial: Compile and Run
Programming in C++ in the Lab
(Or Compiling and Executing Programs from the Command Line)
As previously mentioned in
the Getting Started guide, you will be
writing your program in C++ using sublime, a simple text editor for
Linux.
If you have not already opened sublime, do so now. Then for each program
you write for the tutorial, follow these instructions:
- Copy the input provided, if any, and paste it into a new
file in the editor.
- Save your file.
- Go to File > Save As...
- If this is your first time to save a program as part of the tutorial,
create a new
folder somewhere within your home directory structure:
- Click on your username in the lefthand panel (for
example, horns180).
- Click the
Create Folder button, and name it
something exciting and descriptive, like Tutorial.
- Hit Enter.
- If you choose, you may further organize your individual tutorial
programs into their own directories---we leave it up to you.
- Give your file a descriptive name with a file type of
.cpp. For example, for your first
program, you might name the file HelloWorld.cpp. Among
other things, the .cpp will tell sublime that the content
of this file is C++ code, and it will enable related editing features.
Hit Save when you are happy with your file name.
- Linux does not handle spaces in file names or directory/folder
names well, so if you use a space you will need to escape it
whenever you access that file or directory. For example, if you name
a file "Hello World.cpp", you will need to type "Hello\ World.cpp".
We recommend "HelloWorld.cpp" or "Hello_World.cpp" instead.
- Add your code.
- Compile your code.
- Compiling is converting it from the (sort of) English version
you typed into the language understood by the machine (which is all 0s
and 1s).
- The output of a successful compilation will be
an executable file. This is what you will use to run, or
execute, your program.
- To compile, do the following:
- Make sure your files are saved!
- Open a new terminal window by clicking on the terminal icon again.
- Navigate to the directory where you saved
your file using the commands we talked
about here under Linux
Commands.
- Once you're in the same directory as your file, begin typing in the
following:
g++ <filename> -o <executableName>
- Replace <filename> with the name of the file you
have been editing, and replace <executableName> with
something similarly descriptive. For example, for your HelloWorld
program, you might compile with the following:
g++ HelloWorld.cpp -o HelloWorld
- Check the output in the terminal to see if the build was a success.
If it was not, one or more errors will be printed to the terminal.
See if you can understand and then fix the given errors. If you can't,
please ask us! Compiler errors are famously hard to decipher.
- Run your program.
- Many things can go wrong when you are programming, so please
ask for help before you get frustrated! (Just turn your cups to red!)
|