1.7 KiB
1.7 KiB
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: ~10–15 minutes
Step 1 — Write the program
cd ~/my-project
nano greet.cpp
Type this in:
#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
clang++ -Wall greet.cpp -o greet
-Wallturns on warnings (catches mistakes)-o greetnames the output filegreet
If there are no errors, no message is printed — that's good!
Step 3 — Run it
./greet
Type your name and press Enter. It should say hello back.
Step 4 — Create a Makefile
nano Makefile
Type this:
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
make clean
make
make clean deletes the old greet binary. make rebuilds it.
Step 6 — Run again (via make build)
./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
Makefileto automate the build - Using
makeandmake clean