Build and run your first application with g++

This example shows you how to create a Hello World application with having the logic of hello world in a separate C++ files called hello.h the header file and hello.cpp the implementation file.

Let’s start coding. However you can find following code here in My C++ Tutorial in Github.

First make sure gcc is installed on your machine. g++ command will be installed as a part of gcc package.

  • MacOS: brew install gcc
  • Linux:
    • Debian/Ubuntu: apt-get install gcc
    • CentOS/Fedora/Redhat: yum install gcc
  • Windows: Install Cygwin or MingW

If gcc and g++ are installed correctly, you should be able to check their version using following commands:

$ g++ --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include/c++/4.2.1
Apple LLVM version 10.0.1 (clang-1001.0.46.4)
Target: x86_64-apple-darwin18.2.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

$ gcc --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include/c++/4.2.1
Apple LLVM version 10.0.1 (clang-1001.0.46.4)
Target: x86_64-apple-darwin18.2.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

The first step is create the header file called hello.h . The hello.h header file contains only one line which describes the hello() function signature in abstract level. Make sure hello.h contains following line:

hello.h
void hello();

After that create hello.cpp which is the implementation of hello.h header file. There you need to implement hello() function that contains body:

hello.cpp
#include 
#include "hello.h"

void hello(){
    std::cout << "Hello World!\n";
}

The last part is creating main.cpp file which in this file you call hello() function that you implemented in hello.cpp. That prints Hello World! in the output.

main.cpp
#include "hello.h"

int main (void){
    hello();
}

Now it's time to compile your source code and make it executable. For compiling C source codes you can use gcc command, but for C++ source codes, you need to use g++ compiler command. Here are the instruction to compile the files you have just created to Hello World application.

Using -c you can compile your shared library that typically it shouldn't be executable and having main method. Here is an example:

$ g++ -c hello.cpp

The output will be hello.o file. Now, use following g++ with -o option to specify the executable file name you want to run and also add hello.o shared library file, so that g++ compiler link all files into one executable file called greet.

$ g++ -o greet main.cpp hello.o

Finally, you can run your compile greet app using following command:

$ ./greet
Hello World!

Find the complete source code here in Github.

Leave a Reply