Search code examples
c++makefilecmakecompilationninja

How to compile "Hello World" in C++ with Ninja?


I'm new with Ninja. Still don't know how to use it.

I created a simple hello.cpp file:

#include <iostream>
int main()
{
        std::cout << "Hello World!" << std::endl;
        return 0;
}

I am using Linux Ubuntu.

I have installed CMake with: apt install cmake

and I have installed ninja: apt-get install ninja-build

But now what should I do to compile my hello.cpp file with Ninja?

I tried to run ninja but I'm getting error about rules.ninja:

ninja: error: build.ninja:30: loading 'rules.ninja': No such file or directory

I don't know how to create rules.ninja and how to configure it, and I don't know if I miss more things.


Solution

  • Assuming here that you do not have a CMakeLists.txt file at all. To compile this program, you first need to create a CMakeLists.txt file. This file is used by CMake to configure the project.

    CMakeLists.txt (place it in the same folder as your source files):

    cmake_minimum_required(VERSION 3.8)
    project(my_exe)
    set(CMAKE_CXX_STANDARD 14) # Try 11 if your compiler does not support C++14
    add_executable(my_exe hello.cpp)
    

    Then you need to invoke CMake (in the terminal, go to the folder containing the CMakeLists.txt file) and later build the project.

    First, you should create a build directory. This is handy since you don't want to mix build output with your project files.

    mkdir build
    cd build
    

    Then, you invoke CMake and tell it to generate a Ninja build system (-GNinja), while at the same time tell it where the CMakeLists.txt file is located (..), which should be directly below the build folder:

    cmake -GNinja ..
    

    Now, you are ready to build the executable:

    ninja
    

    Done. You should now have an executable name my_exe in your build folder.