Home CPSC 340

Compiling C++ Programs

The Basic Commands

The "clang++" command compiles a C++ source file on our system. The basic usage is:
$ clang++ filename.cpp
This produces an executable file called "a.out" which can be run with:
$ ./a.out
Try downloading the "Hello World!" program by running the following command and then compiling and running it.
$ wget http://cs.umw.edu/~finlayson/class/spring17/cpsc340/samples/hello.cpp
In order to have an executable named something other than "a.out", you can use the -o flag to specify the output file name:
$ clang++ filename.cpp -o filename
The common convention with UNIX is that executable files have no extension, though you can use an extension if you like.

Error Messages

If your program has any errors, they will be reported by the clang++ command with the line number and a message which describes the problem. Try compiling the following program which has a couple of compilation errors:

$ wget http://cs.umw.edu/~finlayson/class/spring17/cpsc340/samples/broken.cpp
$ clang++ broken.cpp

See if you can fix the errors with this program to get it to compile and run.


Exercise

Write a program to read in numbers from the user, and print the average to the screen. Your program will need to use cin and cout for doing input and output, as well as variables and a loop.

An example run is shown below:

$ ./a.out
Enter number of elements: 4
Enter value: 3
Enter value: 12
Enter value: 27
Enter value: 5
Average is 11.75

Submitting

When your program works, email the code to ifinlay@umw.edu.

Copyright © 2018 Ian Finlayson | Licensed under a Creative Commons Attribution 4.0 International License.