cheatsheet/cpp-exercise.md

103 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# C++ Exercise — "Hello, You!"
**Goal:** Write, compile, and run a C++ program that asks for your name. Then automate the build with a Makefile.
**Time:** ~1015 minutes
---
### Step 1 — Write the program
```bash
cd ~/my-project
nano greet.cpp
```
Type this in:
```cpp
#include <iostream>
#include <string>
int main() {
std::string name;
std::cout << "What is your name? ";
std::getline(std::cin, name);
std::cout << "Hello, " << name << "!" << std::endl;
return 0;
}
```
Save: **Ctrl + O**, then **Enter**
Exit: **Ctrl + X**
### Step 2 — Compile it
```bash
clang++ -Wall greet.cpp -o greet
```
- `-Wall` turns on warnings (catches mistakes)
- `-o greet` names the output file `greet`
If there are no errors, no message is printed — that's good!
### Step 3 — Run it
```bash
./greet
```
Type your name and press **Enter**. It should say hello back.
### Step 4 — Create a Makefile
```bash
nano Makefile
```
Type this:
```make
CXX = clang++
CXXFLAGS = -Wall -std=c++20
TARGET = greet
$(TARGET): greet.cpp
$(CXX) $(CXXFLAGS) greet.cpp -o $(TARGET)
clean:
rm -f $(TARGET)
.PHONY: clean
```
**Important:** The indented lines must use a **Tab** character, not spaces.
Save and exit (**Ctrl + O**, **Enter**, **Ctrl + X**).
### Step 5 — Build with make
```bash
make clean
make
```
`make clean` deletes the old `greet` binary. `make` rebuilds it.
### Step 6 — Run again (via make build)
```bash
./greet
```
---
**Commands you used:** `nano`, `clang++`, `./` (run), `make`, `make clean`
**What you learned:**
- Writing a basic C++ program with input and output
- Compiling with `clang++` and useful flags
- Creating a `Makefile` to automate the build
- Using `make` and `make clean`