Cross-Compiling Zig and C with CMake for STM32 Embedded Systems

I have a personal project where I use Zig for a few purposes described in another topic.

After many experiments, I ended up with a custom CMake module file zig-module.cmake that adds an add_zig_module function that seems “reasonably” functional for incorporating Zig code into a CMake based project.

This CMake solution is not perfect, especially when translating libc headers or compiler specific code. Some CMake generator expressions must also be filtered in certain cases because they cannot be used with add_custom_command.

Example project : juicy_hello_world_cmake

More details of how it works and the source code are available on Github.

I have tested it with the Unix Makefiles and Ninja backends. I also had some success with the Raspberry Pi Pico SDK (pico-sdk).

Observation and conclusion

  • C libc headers integration: wint_t type unknown when I provide my libc headers. I added the definition manually. Missing macro definitions ?
  • CMSIS uses compiler specific features based on macro definitions (GCC, Clang, etc.). How should they be translated correctly ?

It can be a starting point for people trying to do the same thing with CMake. If so, don’t hesitate to share any problems you encountered. I am interested. Suggestions, fixes, and improvements are welcome.

Other experimental examples to integrate Zig on a STM32 projects are also present in the repository.

AI / LLM usage disclosure

I have sometimes used AI cautiously as a search engine and for text corrections.

3 Likes