The first session clarifies what happens between the moment we type text into an editor and the moment the computer executes a program. Understanding the four stages - writing, compiling, linking, execution - explains most of the errors you will run into for the rest of the semester.
1Lab objectives
- Installing and configuring a C/C++ development environment
- Following the four stages through to a working executable file
- Telling compilation errors apart from linking errors
- Recognizing syntactic units: identifiers, keywords, operators, constants
- Writing, compiling, and running your first program
2Working environment
- IDE Code::Blocks or Visual Studio
- C GCC / MinGW compiler
- C++ G++ compiler
- alt. Text editor + command line
Compiling from the command line
If you want to see the stages explicitly, use the terminal:
gcc program.c -o program.exe then ./program.exe3The stages of producing an executable
| Stage | What it does | Result | Typical errors |
|---|---|---|---|
| Writing | writing the code in an editor or IDE | .cpp file | - |
| Preprocessing | expands #include and #define | expanded source code | header file not found |
| Compilation | translates the source into machine code | .obj file | wrong syntax, incompatible type, undeclared variable |
| Linking | links object modules and libraries together | .exe file | function declared but not defined, missing main |
| Execution | loads the program into memory and runs it | - | division by zero, invalid memory access |
How to tell which stage you got wrong in
A message pointing to a line number in your file is a compilation error.
A message like
undefined reference to ..., with no line number, is a linking error:
the function was declared, but its body was not found anywhere.4Basic elements of the language
Writing a program uses syntactic units that fall into a few categories:
| Category | Description | Examples |
|---|---|---|
| Identifiers | names given to types, variables, functions | radius, _maxx, a5, A_B_C |
| Keywords | reserved identifiers, with predefined meaning | int, while, return, class |
| Punctuation marks | delimit regions of code | [ ] ( ) { } , : ; # |
| Whitespace | separators, improve readability | space (32), tab (9), newline (10) |
| Operators | specify the operations performed | + - * / % = == && |
| Constants | fixed values, numeric or strings | 23, 3.14, 'A', "text" |
Rules for identifiers
| Identifier | Valid? | Reason |
|---|---|---|
Radius | yes | starts with a letter |
radius | yes | different from Radius - the language is case sensitive |
_maxx | yes | can start with an underscore |
a5 | yes | the digit is not in the first position |
5a | no | the first character is a digit |
A%B | no | % is not an allowed character |
Case sensitiveC/C++ distinguishes between uppercase and lowercase.
Total, total, and TOTAL are three completely distinct
variables. This is a frequent source of "undeclared variable" errors for beginners.5Program structure
The general structure of a program is made up of three zones:
| Zone | Contents | Mandatory? |
|---|---|---|
| I - preprocessing directives | #include, #define | optional |
| II - global declarations | types, function prototypes, global variables | optional |
| III - function definitions | function bodies, including main() | mandatory |
The main() functionProgram execution always starts with
main(). It is unique and cannot be overloaded. Unlike Pascal, in C/C++ functions
cannot be defined one inside another.6The first program
first.c - the C version
#include <stdio.h> // zone I: preprocessing directives
#define PI 3.14159 // symbolic constant
int runCount = 0; // zone II: global variable
int main(void) // zone III: definition of the main function
{
float radius, area; // local declarations
printf("Enter the radius: ");
scanf("%f", &radius);
area = PI * radius * radius;
printf("Circle area = %.2f\n", area);
return 0; // 0 = program finished successfully
}
first.cpp - the C++ version
#include <iostream>
using namespace std;
const double PI = 3.14159; // in C++, const is preferred over #define
int main()
{
double radius, area;
cout << "Enter the radius: ";
cin >> radius;
area = PI * radius * radius;
cout << "Circle area = " << area << endl;
return 0;
}
The key differenceIn C, input/output is done with functions
(
printf, scanf) that take an explicit format. In C++, streams are
used (cout, cin), and the type is deduced automatically by the
compiler - safer and more convenient.7Code workshop
Here you can write and run C code directly on the page. The program runs in the browser, with no compiler installed: press Run and watch the output below. The Step by step button executes the program instruction by instruction and shows, on the right, the value of each variable at that moment.
Try thisTry removing
\n from the first printf and run it
again. Notice that the two lines end up on the same line - \n is the only thing
that moves the cursor to the next line.8Work tasks
- Install the development environment and create a new console application project.
- Write, compile, and run the program that computes the area of a circle.
- Intentionally delete a
;character and read the error message - note the line indicated. - Call a non-existent function (for example
compute();) and observe that the error occurs at link time, not at compile time. - Check that the language is case sensitive: declare
int sum;and useSum. - Test which of the identifiers in the table above are accepted by the compiler.
- Write the same program in both versions, C and C++, and compare the size of the resulting executable.
9Extended application
ExtensionWrite a program that reads the radius and prints, in an aligned
table, the circle's area and circumference, and the sphere's surface area and volume. Use
#define for PI and %8.3f formatting for alignment. Compare the
results with those obtained using M_PI from <math.h> and
explain any differences.