3 ms·
Ask HN: Extending C
Just for fun, I'd like to extend C with a few control structures, wrapper functions, and maybe even overload bits of the standard library. What's the most portable way to do this? A header file? Writing some preprocessor code?
- yan 17y agoWrap some preprocessor macros in a header file, if you must. Or use a macro language to preprocess your source, such as m4, although that's probably dirty.
- acg 17y agoPerhaps the way that C++ started (CFront): write a front-end to the language that maps your additional language constructs to C. Another lesson from C++ (there are probably many) is to be careful with C compatibility, it's not always as easy as it seems.
- russell 17y agoI second the notion of a front-end like CFront. It's a fun exercise. It took me about a week to do a Pascal to C translator a couple of decades ago. One problem is that the grammar for C is not context free. If you are using a top down parser, it's probably manageable, If you are using yacc, bison or the like, you will probably need some kind of parser or lexer hack. Unfortunately, I cant remember where the problem lies. Ordinarily I would recommend getting a ready-made parser, but they usually generate an abstract syntax tree and often throw away things like formatting and comments that you want in your generated code. I also recommend using Python or your favorite scripting language. Doing it in C hurts the flexibility that you want in your experimentation.
- jacquesm 17y ago'overloading' the standard library is simply a matter of some #defines that make funcx call my_funcx, that's easy. If you want to mess around with language features such as control structures and such then you probably will have to write a pre-processor of your own that parses your language accurately and outputs the corresponding 'C' code. The macro system will quickly run out of steam when you start doing things like that.