How to Write a C Module and Build it with Meson
In this post I put my latest C project skeleton, you can find a github repo for the this tiny project here: https://github.com/rayed/c_module_meson
To build this project you should install “meson”, and of course C compiler.
Build and Run
meson build
cd build
meson compile
./numbers
Meson File “meson.build”
project('numbers', 'c')
glib2 = dependency('glib-2.0')
executable('numbers',
sources: ['main.c', 'numbers.c'],
dependencies : [glib2]
)
The project doesn’t really need “glib2” library, but I included it here for reference.
The name you should put dependency
section is the one for pkg-config, if you aren’t sure
type pkg-config --list-all
and find the library name you want to use.
Header File “numbers.h”
#ifndef NUMBERS_H
#define NUMBERS_H
#include <stdint.h>
#include <stdbool.h>
typedef void (*numbers_print_cb) (uint32_t, uint32_t);
struct numbers_s ;
typedef struct numbers_s numbers_t;
numbers_t * numbers_init();
void numbers_free(numbers_t * ns);
bool numbers_add(numbers_t * ns, uint32_t number);
void numbers_print(numbers_t * ns);
void numbers_print_custom (numbers_t * ns, numbers_print_cb cb);
#endif /* NUMBERS_H */
The first two lines, and the last are what is known as Include guard, it is used to avoid defining resource multiple time when the file included from multiple parts.
numbers_init
is used to initialize the module and return pointer to the module structure, this pointer
or handle we will be used in all subsequent calls.
numbers_free
should be used to release all memory allocated by the module, either directly or indirectly.
Source Code File “numbers.c”
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include "numbers.h"
#define MAX_NUMBERS 128
struct numbers_s {
uint32_t numbers_count;
uint32_t numbers[MAX_NUMBERS];
};
typedef struct numbers_s numbers_t;
numbers_t * numbers_init() {
numbers_t * ns;
ns = calloc(1, sizeof(numbers_t));
return ns;
}
void numbers_free(numbers_t * ns) {
free(ns);
}
bool numbers_add(numbers_t * ns, uint32_t number) {
if (ns->numbers_count >= MAX_NUMBERS) {
return false;
}
ns->numbers[ns->numbers_count++] = number;
return true;
}
void numbers_print(numbers_t * ns) {
for (uint32_t i=0 ; i < ns->numbers_count ; i++) {
printf("%d : %d\n", i, ns->numbers[i]);
}
}
void numbers_print_custom(numbers_t * ns, numbers_print_cb cb) {
for (uint32_t i=0 ; i < ns->numbers_count ; i++) {
cb(i, ns->numbers[i]);
}
}