Welcome. Letβs demystify compiling without making it a whole thing. If you can run a couple terminal commands, you can compile C++.
What compiling is
Your C++ file is readable to you. Your computer wants machine code. Compiling is the translation step that turns your .cpp into something your OS can execute.
In practice, this is you telling a compiler:
βTake these source files and give me a runnable program.β
The compiler you will actually use: g++
g++ is the common C++ compiler command on Linux and macOS (and on Windows if you are using something like MinGW or WSL).
General shape:
g++ [flags] [source files] -o [output_name]
Flags you will see a lot
-Wall
Show helpful warnings. Use it. Future you will thank you.-O2
Optimizes the build (faster program, sometimes slower compile).-std=c++20(orc++17)
Picks the C++ language standard.
Example:
g++ -Wall -O2 -std=c++20 main.cpp -o app
Output names, because this trips everyone once
The -o flag sets the name of the program you are creating.
g++ main.cpp -o app
-
appis now your executable. - Run it like this:
./app
Quick correction on file extensions
If you do not use -o, g++ does not create a .o file by default. It creates an executable named a.out:
g++ main.cpp
./a.out
A .o file is an object file, and you usually only get those when you compile with -c:
g++ -c main.cpp -o main.o
That is useful for multi file projects, but you can ignore it for your first few builds.
A step by step example
- Go to the folder with your code:
cd directory_name
- Compile:
g++ -Wall -std=c++20 filename.cpp -o filename
- Run:
./filename
Compiling with tests (GoogleTest)
If you are linking GoogleTest manually, a simple pattern looks like this:
g++ -Wall -std=c++20 main.cpp tests.cpp gtest_main.a -pthread -o tests
Notes:
-
-pthreadis commonly needed for GoogleTest. -
gtest_main.aprovides a defaultmain()for running tests. - Depending on your setup, you might link
-lgtest -lgtest_maininstead of using a.afile. It varies by install method.
Wrap
Compiling is just turning your code into something runnable. The terminal commands look scary exactly one time, then they are just part of your muscle memory.
If you want, paste the exact command you are using and the error you get. I can translate it into plain English and tell you the one line fix.
For more tutorials, visit https://nessakodo.com
Love,
NESSA KODO
Top comments (0)