Legacy C++ › 1. Getting Started
Program Structure and Compilation
main(), headers, the compile-link process and your first program.
Explanation
A C++ program is one or more translation units (.cpp files). Building it has three stages:
- Preprocess:
#includeand#defineare expanded into plain text. - Compile: each translation unit becomes an object file (
.o/.obj). - Link: object files and libraries are combined into one executable.
Execution starts in main. It returns int; 0 means success. Unlike other functions, main may omit its return and then returns 0 implicitly.
Example
#include <iostream> // declares std::cout
int main(int argc, char* argv[]) {
std::cout << "Hello, C++!\n";
std::cout << "Arguments: " << argc << "\n";
for (int i = 0; i < argc; ++i)
std::cout << " argv[" << i << "] = " << argv[i] << "\n";
return 0;
}
Build and run with GCC: g++ -std=c++03 hello.cpp -o hello. With Visual C++: cl /EHsc hello.cpp.
Common pitfalls
- Using
<iostream.h>: that is pre-standard. Use<iostream>andstd::. void main()is not standard C++;mainmust returnint.- Linker errors such as “undefined reference” mean a function was declared (compiler is happy) but never defined in any file you linked.
- Compiler errors and linker errors are different problems. Read which tool reported it.
Legacy vs modern
Nothing about this changes in modern C++, except that new standards add -std=c++17 style flags and modules (C++20) can replace #include.
Exercises
1. What is the difference between a declaration and a definition of a function?
A declaration (int f(int);) tells the compiler the name and signature. A definition (int f(int x) { return x; }) provides the body. A function may be declared many times but defined once.
2. What does argv[0] usually contain?
The name or path used to start the program.