Meson Tutorial for Beginners Pt. 2

Nov 10, 2025 · meson

Now, let’s move on and add more C files in this project. Because you will have many files in the normal project, otherwise you can manage the compilation of a single file via a command and you don’t need the build system!

Go ahead and create a new file with name greetings.h and write the following code.

#ifndef GREETINGS_H
#define GREETINGS_H

void greet(void);

#endif

We have defined a greet() function prototype in this header file. Let’s create a corresponding greetings.c file where we’re going to actually define this greet() function.

#include "greetings.h"
#include <stdio.h>

void greet(void) {
  printf("hello, world\n");
}

The new file is ready to be consumed! Go back to the main.c file, and let’s use the greetings.h header file and the greet() function. Also, we can remove the use of the stdio.h header file because we are no longer using any function from this header file.

#include "greetings.h"

int main(void) {
  greet();

  return 0;
}

Finally, we need to add this greetings.c file in meson.build and within the executable() function as the next argument. Note: you don’t have to list the header files here.

project('hello-meson', 'c')

executable('main', 'main.c', 'greetings.c')

executable() function takes any numbers of source files.

Go back to the terminal and run.

meson compile -C builddir

Meson will notice the changes, automatically reconfigure if needed, and compile both main.c and greeting.c files. We can run our program as,

./builddir/main
hello, world

Let’s do some refactor now.

As of now, we have two files — main.c and greetings.c files. But, as the project grows, we will have 10 or 20 files or maybe 100+ files. Listing every single file inside the executable() function can become messy. Let’s use variables instead! Create a variable with name srcs, that will hold the list of source files. As it is a list, it needs to be defined with [] as,

project('hello-meson', 'c')

srcs = [
 'main.c',
 'greetings.c'
]

executable('main', srcs)

Let’s compile and re-run to confirm that our changes work as expected.

meson compile -C builddir
./builddir/main
hello, world

Yay!