Prerequisites
- GCC compiler
- For Windows, you will need to install
mingw
- For Linux, you will need to refer to your distributions package manager
- For Mac, you will need to use
brew
- For Windows, you will need to install
Compiling C++ Using Terminal
First, let's make a simple C++ file named
main.cpp
// main.cpp #include <iostream> int main() { std::cout << "Hello World!\n"; }
Now, open your terminal in the same directory where the file was saved.
To compile the file
$ g++ main.cpp
You can replace
main.cpp
with the filename you chose. This will compile your file into an executable calleda.out
Finally, to run the file
$ ./a.out
Incase you want to name the executable file
$ g++ main.cpp -o main
This will make the executable file as
main
Compiling C++ Files with Header Files
You've divided your main file into multiple files. Now what?
I created a new file called
Universe.hpp
inincludes
directory andmain.cpp
intosrc
directory My directory now looks like. ├── includes │ └── Universe.hpp └── src └── main.cpp
// Universe.hpp #pragma once #include <iostream> class Universe { public: Universe() { std::cout << "Hello Universe\n"; } };
and I changed my
main.cpp
to// main.cpp #include <iostream> #include "Universe.hpp" int main() { std::cout << "Hello World!\n"; Universe universe; }
If I compile my main file now, I get an error
What this means is that gcc can't find my
Universe.hpp
file, we need to tell where the file is.To tell gcc where are header files are located, we will use
-I
flag$ g++ src/main.cpp -I includes
It compiles just fine with no errors and runs as well!
Conclusion
g++
is used to compile C++ on terminal-o
flag is used to name output executable-I
is used to include header files directory