Using meson as a build system with CLion
At work I started a green field C++ project using the meson build system. Unfortunately my favorite IDE CLion only supports integration with CMake out of the box. However with a bit of try and error I could make my favorite features work.
The trick to make code completion and other features work with meson is to use the compilation database support built into CLion. Now the database is just a json file listing describing all necessary commands to build the project. Luckily, meson supports generating one out of the box.
For this tutorial I will use the tiny sample project from
meson docs as an example. So we start out with some code and a matching meson.build
file:
// ./main.c
#include<stdio.h>
int main(int argc, char **argv) {
printf("Hello there.\n");
return 0;
}
# ./meson.build
project('tutorial', 'c')
executable('demo', 'main.c')
Now as a first step we need to create a build directory using meson. This should be familiar for anyone using meson
$ meson
The Meson build system
Version: 0.52.0
Source dir: /meson-example
Build dir: /meson-example/builddir
Build type: native build
...
Now, in your newly created build directory there should be a compile_commands.json
, that is your compilation database.
If it was not created, its pretty easy to generate:
The build tool used by meson, ninja has built-in support for generating them
$ cd builddir
builddir $ ninja -t compdb c_COMPILER cpp_COMPILER > compile_commands.json
The file should look something like this
[
{
"directory": "/meson-example/builddir",
"command": "cl @demo@exe/main.c.obj.rsp",
"file": "../main.c"
}
]
That should already be enough to open the project in CLion. For this, open a new project in CLion by selecting the
compile_commands.json
file and selecting "Open as project".
Next you need to change the project root, because clion automatically picks the directory containing the compilation
database as project root. The project root can be changed using the Tools -> Compilation Database -> Change Project Root
menu entry.
And that's pretty much it! If you change your meson.build files you will need to recreate the compilation database. One
way to do this is using the File Watchers plugin. On any
change to your meson.build
, you can run ninja reconfigure
and ninja -t compdb c_COMPILER cpp_COMPILER
. CLion can
also automatically reload change to the database, so it will automatically re-index all the files.
Trouble detecting the compiler on some linux systems
When I first tried this method on my fedora based system, it did not work because CLion failed to recognize the ccache
command as a transparent cache for the following gcc
command line. To fix this I head to tell meson
to just use
gcc
instead of ccache gcc
.
This can be done by deleting the build directory and passing the CC
and CXX
variables to the initial build directory
setup.
$ rm -rf builddir
$ CC=gcc CXX=g++ meson builddir