Adding Moxy to an existing C project
You don't rewrite anything. You pick one .c file, write its replacement as a .mxy file, teach your build to turn that file into C, and delete the old one. The rest of the project keeps compiling as before, and you can stop after any file.
Everything here is exercised by examples/adoption, a small C program with three variants:
| Directory | What it is |
|---|---|
before/ |
the plain C project, with a Makefile and a CMakeLists.txt |
after/ |
the same project with words.c replaced by words.mxy, with a Makefile and a CMakeLists.txt |
library/ |
the same port built as a separate Moxy project that produces a static library |
sh examples/adoption/check.sh builds all of them and checks that each prints the same output. Run it with MOXY=/path/to/moxy. Make and CMake were tested with CMake 4.5. Meson was not tested; see Meson.
How the pieces fit
moxy emit file.mxy -o file.c writes one C file for one .mxy file, including any .mxy files it #includes. The output is ordinary C11 with no dependency on a Moxy installation: the runtime it needs is embedded in the file. Any build system that can run a command to produce a .c file can use it.
Three consequences to plan around:
- Each emitted file carries its own copy of the runtime. It is about 1,300 lines in the sample, all
static, so copies in different files never collide at link time. It also means two separately emitted files do not share types. Pass only C types between them and between Moxy and C: integers, floats, pointers, plain structs, andconst char *. To share Moxy values (string[],map,Result) between files, put them in one translation unit by#includeing the.mxyfiles into a single entry file. - A
const char *that comes from C is not a Moxystring. A Moxystringhas a header in front of its bytes. If you declare a parameter asstringand C passes a literal,s.lenreads garbage. In a function that C calls, takeconst char *sand copy it into a managed value on the first line:string text = s;. The sample'swords.mxydoes this. Returning strings from Moxy to C is not covered here. - Errors point at your
.mxyfile. The generated C carries#linedirectives, so both Moxy and C compiler diagnostics (and debuggers) namewords.mxy:12, notwords.c:812.
Step 0: install and check
moxy --version
cc --version
Keep your C compiler and flags as they are. Moxy generates C and your compiler builds it, so cross-compilation, sanitizers and -Werror settings carry over. If the link fails with undefined pthread or m symbols, add -pthread or -lm; the former is needed when you use Future.
Step 1: port one file
Choose a leaf: a .c file with a small interface and no global state that other files poke at directly. Keep its header. The header is the contract every other file already compiles against.
before/src/words.c:
#include <ctype.h>
#include "text.h"
int count_words(const char *s) {
int n = 0, in_word = 0;
for (; *s; s++) {
if (isspace((unsigned char)*s)) in_word = 0;
else if (!in_word) { in_word = 1; n++; }
}
return n;
}
after/src/words.mxy:
#include "text.h"
// s comes from C, so it is a plain char pointer. Assigning it to a string
// copies it into a managed string.
int count_words(const char *s) {
string text = s;
int n = 0;
bool in_word = false;
for (long i = 0; i < text.len; i++) {
char c = text[i];
if (c == ' ' || c == '\t' || c == '\n') {
in_word = false;
} else if (!in_word) {
in_word = true;
n++;
}
}
return n;
}
#include "text.h" is passed to the C compiler unchanged: moxy emit copies the line into the generated C and does not look for the file. Your C compiler finds it through the -I flags you already use (-Isrc in the recipes below), and checks the function against the declaration in the header.
Check the generated C before you wire anything up:
moxy emit src/words.mxy | less
The function comes out as a normal external function, int count_words(mxy_str s), where mxy_str is const char *.
Make
Add two pattern rules. after/Makefile:
MOXY ?= moxy
CC ?= cc
CFLAGS ?= -O2 -Wall -std=c11
HDR := $(wildcard src/*.h)
MXY := $(wildcard src/*.mxy)
CSRC := $(wildcard src/*.c)
OBJ := $(CSRC:src/%.c=build/%.o) $(MXY:src/%.mxy=build/%.o)
app: $(OBJ)
$(CC) $(OBJ) -o $@
$(OBJ): $(HDR)
build/%.o: src/%.c
@mkdir -p build
$(CC) $(CFLAGS) -Isrc -c $< -o $@
build/%.c: src/%.mxy $(MXY)
@mkdir -p build
$(MOXY) emit $< -o $@
build/%.o: build/%.c
$(CC) $(CFLAGS) -Isrc -c $< -o $@
.SECONDARY:
Every .mxy file is a prerequisite of every generated .c, so editing a file that another one includes regenerates both. .SECONDARY stops make from deleting the generated C, which you will want to read. To port the next file, write src/foo.mxy and delete src/foo.c. The rules pick up the change without edits.
If your Makefile lists sources by name rather than with wildcard, replace foo.o with build/foo.o built from foo.mxy through the same rules.
CMake
Wrap the command in a function and add its output to the target. after/CMakeLists.txt:
find_program(MOXY moxy REQUIRED)
function(moxy_sources out)
set(generated)
foreach(src IN LISTS ARGN)
get_filename_component(name ${src} NAME_WE)
set(c ${CMAKE_CURRENT_BINARY_DIR}/moxy/${name}.c)
add_custom_command(
OUTPUT ${c}
COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/moxy
COMMAND ${MOXY} emit ${CMAKE_CURRENT_SOURCE_DIR}/${src} -o ${c}
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${src} ${CMAKE_CURRENT_SOURCE_DIR}/src/text.h
COMMENT "moxy emit ${src}"
VERBATIM)
list(APPEND generated ${c})
endforeach()
set(${out} ${generated} PARENT_SCOPE)
endfunction()
moxy_sources(MOXY_C src/words.mxy)
add_executable(app
src/main.c
src/lower.c
${MOXY_C}
)
target_include_directories(app PRIVATE src)
Adding src/foo.mxy is one more argument to moxy_sources and one fewer file in add_executable. DEPENDS lists only the one header here; list the .mxy files and headers that each file includes.
The generated C compiles under whatever CMAKE_C_FLAGS you already set. The sample's generated file builds without warnings under -Wall -Wextra -Werror; larger programs have not been checked, and a warning in generated code is a bug worth reporting.
Meson
Untested. Meson is not installed on the machine this guide was written on, so this recipe has not been run. It uses the same mechanism as the other two and should work with a custom_target:
moxy = find_program('moxy')
words_c = custom_target('words',
input: 'src/words.mxy',
output: 'words.c',
command: [moxy, 'emit', '@INPUT@', '-o', '@OUTPUT@'],
depend_files: ['src/text.h'])
executable('app', ['src/main.c', 'src/lower.c', words_c],
include_directories: include_directories('src'))
If you try it, send a fix to this page if anything differs.
When the Moxy side grows: a static library
Once several .mxy files belong together, make them a Moxy project of their own and link its library. library/moxy/moxy.yaml:
project:
name: "words"
version: "0.1.0"
type: "lib"
build:
cc: "cc"
cflags: "-Wall"
includes:
- "src"
library/moxy/src/lib.mxy is the entry point and #includes the others. moxy build produces build/debug/libwords.a and a header build/debug/words.h that declares every function whose signature C can express, and marks the others with a comment. moxy build --release writes to build/release/.
The C project then needs one rule to run moxy build and one library on the link line. library/Makefile:
LIB := moxy/build/debug/libwords.a
app: c/main.c c/lower.c c/text.h $(LIB)
$(CC) $(CFLAGS) -Ic c/main.c c/lower.c $(LIB) -lm -o $@
$(LIB): $(wildcard moxy/src/*.mxy) moxy/moxy.yaml
cd moxy && $(MOXY) build
Because the whole library is one translation unit, its .mxy files can share strings, lists, maps and ref structs freely. Only the functions you export cross into C, so keep their signatures to C types. For CMake, run the same two commands from add_custom_command and add the .a to target_link_libraries; the CMake variant of this layout was not tested.
What to port first
Good first files:
- string handling, parsing and formatting code, where
string,splitand interpolation replace buffer arithmetic; - tables and lookup code that is a hand-rolled hash map or growable array;
- anything with a long
goto cleanuptail, wheredeferand automatic release remove the tail.
Leave for later: files that expose structs with pointer fields owned by other C code, and anything that depends on __attribute__ or _Alignas on declarations. Those need to stay in headers; see Working with C.
Testing the port
Keep the old C file's tests running against the new file. For the Moxy side, .mxy tests under tests/ run with moxy test, and moxy test --sanitize runs them under AddressSanitizer and UndefinedBehaviorSanitizer. Your existing C test binary links the generated C like any other object, so sanitizer flags you already pass to your C compiler apply to it too.