Compiling C++ Using Terminal

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

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

    // main.cpp
    #include <iostream>
    
    int main()
    {
      std::cout << "Hello World!\n";
    }
    
  2. Now, open your terminal in the same directory where the file was saved.

  3. 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 called a.out image.png

  4. Finally, to run the file

    $ ./a.out
    

    image.png

  5. Incase you want to name the executable file

    $ g++ main.cpp -o main
    

    This will make the executable file as main

    image.png

Compiling C++ Files with Header Files

You've divided your main file into multiple files. Now what?

  1. 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
    
    // 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

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

  2. 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! image.png

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