Just like you use CMake (creating a
CMakeLists.txt file) to generate the
Makefile file and then use the
Although you can also use CMake for Ninja too.
You use Meson (creating the meson.ninja file) to generate the ninja.build file and then use the
But how to do that?
How to compile programs with Ninja
Ninja is a small build system with a focus on speed. In essence, Ninja is an alternative to Make. Ninja is used by several projects, having as its main client Google Chrome and Android, and is used by most developers working on LLVM.
The process is very similar to that of Make.
Compiling in C, single file:
Assuming you have this code (Hello, World!) in C:
vim main.c. In this example we use the command [gcc]https://en.terminalroot.com.br/gnu-autotools-ultimate-tutorial-for-beginners/) to compile a single file, but below, see multiple files in C++, which only changes the command and the number of files.
To compile with Ninja, you will need to create a ** build.ninja ** file with the following content:
Analyzing the file above, according to previous knowledge about Make, for example, we noticed that the file that will be compiled we define as: main.c, the temporary file we call src.o and the final binary file we name demo-c.
Now, just be in the directory you saved and via the command line run:
And then just run the program:
There are several options such as cleaning the temporary file(s) and among other options, for more details visit the manual.
Compiling in C++, multiple files:
For this example we will use Dec2Bin, a mini program that converts decimal to binary in C++. In this example we use the command g++ to compile multiple files. There are 3 files, of which 1 is just a
We saved the files inside the dec2bin directory:
In the same way as the previous one, we will create a file build.ninja, only with the following settings:
Then just run the
ninja command and the
program-cpp file will be ready in the same directory. See the output in the image below where we used the program to convert the decimal number: 9 to binary: 1001:
How to Compile Programs with Meson Build
Meson supports GNU Compiler Collection, Clang, Microsoft Visual Studio and others.
How to compile a program with Meson
In the same directory as your code file/project you should create a file named meson.build:
Let’s create the file: tutorial, the language is cpp(C++), the final binary file will have the name: demo and the file we are going to compile is main.cpp.
Once this is done, the next step is to run the command:
The output will look like this:
It will create a directory with the name builddir and we need to enter it to make the build:
After that just run the generated executable file:
For more information and details see the official documentation.
Simple, right? Thanks!