# Compiling C++ Using Terminal

### 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`

### Compiling C++ Using Terminal

0. First, let's make a simple C++ file named `main.cpp`

   ```cpp
   // main.cpp
   #include <iostream>

   int main()
   {
     std::cout << "Hello World!\n";
   }
   ```

1. Now, open your terminal in the same directory where the file was saved.

2. To compile the file

   ```bash
   $ g++ main.cpp
   ```

   You can replace `main.cpp` with the filename you chose. This will compile your file into an executable called `a.out`
   ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1652190691392/pFdF0OAaj.png align="left")

3. Finally, to run the file

   ```bash
   $ ./a.out
   ```

   ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1652190771990/Q_lfP1sCF.png align="left")

4. Incase you want to name the executable file
   ```bash
   $ g++ main.cpp -o main
   ```
   This will make the executable file as `main`
   
   ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1652191559057/-W7ZT1-0M.png align="left")

### Compiling C++ Files with Header Files
You've divided your main file into multiple files. Now what?

0. I created a new file called `Universe.hpp` in `includes` directory and `main.cpp` into `src` directory
   My directory now looks like
   ```
   .
   ├── includes
   │   └── Universe.hpp
   └── src
       └── main.cpp
   ```

   ```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

   ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1652194399706/v3Ohg6jK9.png align="left")

   What this means is that gcc can't find my `Universe.hpp` file, we need to tell where the file is.

1. To tell gcc where are header files are located, we will use `-I` flag
   ```bash
   $ g++ src/main.cpp -I includes
   ```
   It compiles just fine with no errors and runs as well!
   ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1652194579355/v8bETSqYl.png align="left")

### Conclusion
1. `g++` is used to compile C++ on terminal
2. `-o` flag is used to name output executable
3. `-I` is used to include header files directory

