© A.Voß, FH Aachen, codebasedlearning.dev
Three steps turn a text file into a running program:
- Compiling — the compiler (
g++,clang++, MSVC) translates one source file, after the preprocessor has pasted in its#includes, into machine code for your processor. The result is an object file (.o,.obj): machine code, but not yet runnable — calls into other files and into the standard library, such as the output withstd::cout, are still open ends. - Linking — the linker joins the object files and the libraries into one executable and connects the open ends,
so that every call finds its function. Exactly one
mainmust be among them. - Running — the operating system loads the executable into memory and starts it; a bit of start-up code from the
C++ runtime then calls
main. The valuemainreturns goes back to the shell as the exit code.
g++ a_helloworld.cpp -o a_helloworld.out does compiling and linking in one go. The two steps separately:
g++ -c a_helloworld.cpp # compile only: a_helloworld.o
g++ a_helloworld.o -o a_helloworld.out # link: a_helloworld.out
./a_helloworld.out # run
Two consequences. Errors come from different steps: a typo or a type error from the compiler, an undefined reference
(or undefined symbols) from the linker. And the executable is what runs, not the source: change the source and forget
to compile, and you run the old program.
The whole way as a picture is in the README of this unit. More in the
glossary; the linker gets its own look once programs consist of several
files.
Instead of compiling everything every time, use make. It checks what changed and only rebuilds what’s necessary.
The rules and dependencies live in a file called makefile. To use it, just type:
make
Behind the scenes in many IDEs (like CLion), CMake orchestrates the build. CMake isn’t a build system itself — it
generates build files for one (e.g., makefiles). In practice, you mostly edit ../CMakeLists.txt to declare sources,
targets and dependencies; CLion runs CMake and the build tools for you.
- Work in a project of your own, outside this repository. Create one file per task, named after the task, e.g.
westrosecliff.cpp, and add a target for it inCMakeLists.txt. Or build it withg++or amakefileof your own — seei_preparation. - Reading input from the console comes in the
follow_upconsole-sample. Alternatively, define your input values asconstvariables at the top ofmain- change them and rebuild to test other cases. - When you are done, compare your solution with the one in
iv_solutions(once available), and ask an LLM of your choice (ChatGPT, Claude, ...) to review it - paste the task and your code. What does it criticize, and is it right? Check its claims before you believe them. If asked, post on Slido what you have learned.
Open a terminal, change into the i_preparation directory, and compile your first C++ file.
Note: An executable in Windows ends with exe, so replace all out with exe.
Run
g++ a_helloworld.cpp -o a_helloworld.out
This produces an executable named a_helloworld.out. Now launch it:
./a_helloworld.out
If you skip the -o option, the compiler defaults to the very imaginative name a.out — which is fine until you have
three of them and can’t remember who’s who.
Remove a_helloworld.out and build with
make
Create your first C++-project in your IDE. Create or copy a simple C++-source, compile and run it.
- Define a
const int nand aconst char cwith values of your choice. - Test whether
nis greater than0and whethercis an uppercase letter. Use only comparisons on the character itself, e.g.'A' <= c. - Store both results in
boolvariables and output them.
Extension:
- Use the
?:operator instead of anifwhere possible. <cctype>offersstd::isupper. Look up why it takes anintand not achar.
Review: paste the task and your solution into an LLM. What does it criticize, and is it right?
- Write a function
set_valuethat (locally) defines anintwith a value of your choice, and a functionread_valuethat (also locally) defines anintwithout a value and prints it. - Call
set_value, thenread_value. Predict the output first. - Build and run it once as Debug (
-O0) and once as Release (-O2). Explain the difference in two sentences.
Extension:
- Add a second variable to
set_value, before the first one. Doesread_valuestill print your value? Why, or why not?
Review: paste the task and your solution into an LLM. What does it criticize, and is it right?
- Define
bandnasconstvariables of an appropriate type. Calculatebto the power ofnin a loop and output the result. - Write a function
potthat receivesbandnand returns the result. Declare it beforemainand define it aftermain. - Use
constwherever possible.
Extension:
- Formulate the loop once as a
forand once as awhileloop. - For
b=2: from whichnon is the result wrong? Why is there no error message? Compare withunsigned int.
Review: paste the task and your solution into an LLM. What does it criticize, and is it right?
- Define a
constnumbernand calculate the firstnFibonacci numbersf_iiteratively, i.e. in a loop, not recursively, and output them. The rule isf_i = f_(i-1) + f_(i-2)withf_0 = 0andf_1 = 1. - Find the first
ifor whichintis no longer enough. Switch tostd::uint64_tfrom<cstdint>: how far do you get now?
Extension:
- The session computes
fibrecursively. Count how many callsfib(30)needs - with a counter variable defined outside the function, e.g.int calls{0};right above it, and++calls;in the function. Which version is faster, and why? Think of the stack frames.
Review: paste the task and your solution into an LLM. What does it criticize, and is it right?
- Write a function
is_primethat receives a number and returnstrueorfalse. - Test it for several numbers with
assertfrom<cassert>, e.g.assert(is_prime(7));. A failingassertstops the program. - Output all primes below a
constlimit, e.g. 100.
Extension:
- Count the primes below 1'000'000. Measure the runtime in a terminal, once built with
-O0and once with-O2- on macOS and Linux withtime ./pinepoint, on Windows in PowerShell withMeasure-Command { .\pinepoint.exe }. How big is the difference?
Review: paste the task and your solution into an LLM. What does it criticize, and is it right?
A warm-up for working with AI tools - and for not trusting them blindly. Here are two answers to the question "Does this C++ program terminate, and what does it print?", as an LLM might write them:
#include <iostream>
int main() {
int n{0};
for (int i{1}; i > 0; ++i) {
++n;
}
std::cout << "done, n=" << n << '\n';
}Answer A: Yes, it terminates.
icounts up to 2147483647, the largestint; the next increment wraps around to -2147483648,i > 0becomes false, and the program printsdone, n=2147483647. It takes a moment, but it ends.
Answer B: No. Signed overflow is undefined behavior, so the compiler may assume that
i > 0always holds and turn this into an endless loop - the program never prints anything. To fix it, uselong longinstead ofint; then the loop ends correctly.
- Go through both answers statement by statement: which ones are right, which are wrong? Which answer is more useful?
- Run the program yourself, built with
-O0and with-O2(stop it with Ctrl+C if it does not end). Does it confirm your judgement? Compare with someone who uses another compiler. - If you have an LLM at hand, ask it the same question. Is its answer closer to A or to B?
Our results: answers.
- If you have not completed the tasks in the exercise, complete them at home.
- Work through the required study: all
study_*files iniii_follow_up. - If you are curious: the
tinker_*files there.
Answers: comprehension check 0x01.
- I can create, build and run a C++ program, with CMake and with
make. - I can define and initialize variables, and I know why we prefer
{}. - I can explain what an uninitialized variable contains and why reading it is UB.
- I know that the sizes of types depend on the platform, and how to find them out.
- I know the difference between
s[i]ands.at(i), and whatstring::nposmeans. - I can declare and define functions, and I know what a call does on the stack.
- I can predict what happens on integer overflow.
- I know the control structures
if,for,while,do-whileandswitch- and what aswitchwithoutbreakdoes. - I can test with
assert, and I know why anassertmust never do work the program needs.