How To Compile from the Command Line
Often, it is useful to compile a a simple program from the
command line. The steps to do so are listed below.
- Create a folder to contain your source code and executable.
For labs and homework assignments, create a folder on the
Desktop and name the folder as CS120Assignment#YourName with no
spaces. As an example, CS120Lab1JaneDoe.
- Open the Command Prompt program which can be found from in the
Doc - resembles a black window.
- Navigate to the folder you created on the Desktop. You will do
this within the Command Prompt window by using the "cd" command (cd
stand for change directory). The easiest way to do this is to
type "cd " at the
command line and then drag your folder onto the Command Prompt
window. You should see a prompt similar to the one below:
tag4622:~ labuser$ cd
- You can list the contents of your current directory within the
Command Prompt window by typing "ls"
(ls stands for list directory).
- Create your source program using TextWrangler. Save the source
program - If you are creating a C source file the program should
be named with a .c extension.
If the file is a header file it must be named with a .h extension. If the
file is C++ source it should be named with the .cpp extension. Be
sure to save the file in the folder you created on the Desktop.
- To compile a single C++ source file, type in the following
command within the Command Prompt window:
g++ -o Lab1 Lab1.cpp
Here, g++ invokes the C++ compiler, the -o option specifies
the name of the created object file (the executable is Lab1
for this example), and Lab1.cpp is the source file to be
compiled. You should see a prompt similar to the one below:
CS120Lab1JaneDoe$ g++ -o Lab1 Lab1.cpp
- If your source file compiles without
errors then you should find an executable file located in your
directory. You can check this by typing "ls"
to list the directory contents.
- To run your program type "./name of the
executable file" at the Command Prompt. You should see a
prompt similar to the one below:
- For more information on compiling
multiple files or using advanced compiler options type
"man g++" in the
Command Prompt window to see the manual pages for the g++