r/ProgrammingLanguages • u/Salt-Overflow • Jul 26 '26
Adding cyclic modules to the C programming language
https://youtu.be/p8NpyBIRbEQThe idea is to create a module system, within C, that you can use as a drop-in replacement for header files and forward declarations.
To my knowledge, all module implementations within the C family (eg. C++20 modules, Objective C modules, Clang modules) do not allow cyclic imports. Cyclic imports are necessary if you want to remove forward declarations from C (otherwise mutually recursive data structures would need to exist in the same module).
When looking closely at the C grammar, I noticed something extraordinary and borderline miraculous - C without expressions is context-free you can extract the names of symbol definitions without prior access to a symbol table! With this knowledge, it becomes possible to implement cyclic modules within the C language.
EDIT: Added a strikethrough. C without expressions still has some ambiguities in the parameter list, and my use of "context-free" is incorrect here. https://www.reddit.com/r/C_Programming/comments/1v7l174/is_c_without_expressions_contextfree/
View all comments
Show parent comment
2
u/Salt-Overflow Aug 06 '26
Thanks for taking it for a spin! I spend a lot of time trying to cover every case, but I have blind spots and it's really helpful to have a few extra pairs of eyes.
For this prototype, I simplified the grammar so parameters always follow
typename symbolname. I forgot about this special exception. A prototype that works for C99 (minus trigraphs, K&R syntax) is in the works that will resolve this.Borrowing from C++20 modules, the idea is to import the header file directly. Something like
import "math.h";orimport math;looking up the correct file (aside: which syntax do you prefer?). Note that this does not import macros - one could imagine some special syntax#include_macro "math.h"doing that for us.Technically,
export staticis nonsensical, becausestaticmeans the symbol is not visible outside of the module file. Of course, I understand what you mean here. If we want cyclic modules to behave like header files, thenexport statichas a special meaning: importers redefine a new symbol instead of importing a symbol reference. I hadn't thought about adding this feature to my C99 prototype, but now that you mention it, I might just add it in.constexpris a C23 addition, so I hadn't thought about it. But it would work the same way asexport static.