8 ms·
C preprocessor tips and tricks
- tux3 11y agoIt's a good introduction to the preprocessor, but I would dispute that it's advanced tricks. The content is definitely interesting, but also very standard practice. There are many wonderful and horrible things that can be done with macros, and some people get very creative, sometimes to a fault. It's always a special feeling to see macros taking as argument other macros, all of that spreads through a deep hierarchy over several files!
- vmorgulis 11y ago> It's a good introduction to the preprocessor, but I would dispute that it's advanced tricks. Yes. The X macro is missing for example. https://en.wikipedia.org/wiki/X_Macro https://en.wikipedia.org/wiki/X_Macro I would also add #error, #line... and command line options to get the preprocessed output.
- dang 11y ago> I would dispute that it's advanced tricks Ok, we took out "advanced" and put in "C". HN readers are like sandpaper for titles. My thought of the day.
- ape4 11y agoBest to avoid macros if possible. use inline functions. Use global variables instead of MAX_BUF, etc
- _kst_ 11y agoThe name of a variable, global or otherwise, is not a constant expression, so there are contexts in which it can't be used.
- marvy 11y agoNot always possible though. For instance, I don't think it's possible to write "assert" as a function; it has to be a macro. But things like assert are admittedly pretty rare.
- emcrazyone 11y agoI follow the advise of Scott Meyers to prefer the compiler over the pre-processor. Pre-processor code can inject bugs that which can't be easily traced with debugging tools. The pre-processor is pure evil and should be avoided when ever possible.
- PeCaN 11y agoIf you want to debug preprocessor-generated code, -gdwarf-4 -g3 usually does the trick with GCC and Clang. If it doesn't, you can just gcc -E it and run it through clang-format or something, and compile and debug the expanded version. It's really not a big deal. You can have a Makefile rule to do this automatically, for example https://github.com/alpha123/yu/blob/master/Makefile#L70-L103 https://github.com/alpha123/yu/blob/master/Makefile#L70-L103 Saying the C preprocessor can "inject bugs" and make code that "can't be easily traced" is deceptive and wrong. It is, for all intents and purposes, a solved problem. That Makefile rule could be 3x shorter if I didn't go for some extra niceties like not expanding system headers. (As usual, 20% of the result takes 80% of the work). The preprocessor doesn't "inject bugs" anyway, unless you write very careless macros. Modern C, with things like __typeof, _Generic, and GCC/Clang's statement expressions means your macros can be totally safe against overwriting variables, double-evaluation, type errors, and more. You can, of course, still do silly things, but C isn't about protecting the programmer anyway, and that's totally fine if you're prepared for it. Perhaps in C++ the preprocessor is ‘pure evil’, but in C it's a very useful part of the language.
- emcrazyone 11y agoI work in the embedded space and use a compiler from Green Hills. The preprocessor in either C or C++ is evil for the simple matter you can't debug it when the thing you're debugging is in production, symbols are stripped, and the disassemble resembles nothing you can marry up to actual C or C++ code. In simple cases, maybe, but in not so simple cases it's just evil. A modern compiler will optimized out the global consts anyways too...
- kllrnohj 11y ago
- _kst_ 11y ago> #ifdefs don't protect you from misspelled words, #ifs do. That's not (typically) correct. If an undefined identifier is used in a preprocessor expression, it expands (contracts?) to a constant 0. gcc does not warn about using undefined identifiers by default, and if there's an option to make it do so I'm not familiar with it. (EDIT: I am now, it's "-Wundef". Thanks, sigjuice.) For example, this program: #include <stdio.h> #define MISPELLED int main(void) { #if MISPELED puts("MISPELED is true"); #else puts("MISPELED is false"); #endif #ifdef MISPELED puts("MISPELED is defined"); #else puts("MISPELED is not defined"); #endif } produces no compile-time diagnostics and prints this output: MISPELED is false MISPELED is not defined If you have a C compiler that warns about this, that's great -- but you're likely to get spurious warnings for some code.
- sigjuice 11y agogcc has -Wundef (Warn if an undefined identifier is evaluated in an #if directive.)
- PeCaN 11y agoWhich is a enabled by default with -Wall. I'm a fan of compiling with -Wall -Wextra and manually disabling any irrelevant warnings (which is rare, and preferable to do on a per-file basis in the Makefile).
- m6w6 11y agoThe rationale for #if vs #ifdef was interesting, though.
- catwell 11y agoA preprocessor "trick" not mentioned in the article is the use of GNU statement expressions. The article describes the do {} while(0) trick to make macros look like statements. They can then basically be used like inline void function calls. But what if you want to write a macro to replace an inline function that returns a result? Statement expressions [1] solve that problem. Now you can finally do this: int _foo(int x) { return 2 * x; } #ifdef __DEBUG__ # define foo(x) \({ \ int r = _foo(x); \ printf( \ "foo returned: %d (%s:%d)\n", \ r, __FILE__, __LINE__ \ ); \ r; \ }) #else # define foo _foo #endif They are supported by most popular compilers which are not made by Microsoft (including GCC and clang). [1] https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html
- PeCaN 11y agoThe canonical use of which being safe min/max: #define min(a, b) ({ \ __typeof__(a) _a = (a); \ __typeof__(b) _b = (b); \ _a > _b ? _b : _a; \ }) #define max(a, b) ({ \ __typeof__(a) _a = (a); \ __typeof__(b) _b = (b); \ _b > _a ? _b : _a; \ }) which avoid evaluating their arguments twice.
- shortsightedsid 11y ago> A preprocessor "trick" not mentioned in the article is the use of GNU statement expressions. That's probably because IAR sells compilers (and IDEs) for embedded software. IAR and Keil are the popular compilers in the "bare bones microcontroller C/Assembly" world.
- icholy 11y agoProtip #1: don't use them.
- uxcn 11y agoIn C++, probably never. In C, they can be necessary for doing type orthogonal things (like intrusive data structures). Type generic expressions in C11 can be a bit of a safer alternative for some stuff, but you generally need to give explicit implementations for each type. For example, #define sqrt(x) _Generic((x), long double: sqrtl, float: sqrtf, default: sqrt)(x)
- blt 11y agoEven in C++, they are good when you want to encapsulate a statement that may return from the enclosing function. Every time I write a parser or interpreter in C++, I end up writing a macro like #define EXPECT_TYPE(node, Type) if ((node)->type != Type) { return FAIL; } and using it extensively.
- uxcn 11y agoAlso things like generating code at compile time, but a lot of people could argue it both ways.
- sklogic 11y agoYou have to use preprocessor in any non-trivial C++ project. For an idiomatic and very nice and clean example of a heavy preprocessor use see LLVM and Clang code.
- uxcn 11y agoYou don't have to use the preprocessor, but it is definitely practical for certain things. It's probably not clear from my comment, but macros were what I assumed the above post was talking about though (e.g. min/max). FYI, some projects actually eschew the C/C++ preprocessor for other languages. I tend to avoid macros, but stuff like generating things at compile time can sometimes be pretty useful. It can make it harder for other people to read the code if they're not familiar with it though (also any tools that need to parse), which is why I try to prefer using UltiSnips for most stuff I normally might do with a macro.
- maxxxxx 11y agoReading this makes me a little sad. I know the preprocessor can be misused but I really miss it in C#. A lot of highly repetitive code could be written much more elegant with a few well written macros.
- PeCaN 11y agoThere's always M4, which will preprocess just about anything you throw at it. The syntax starts off pretty godawful, but eventually you learn to love it. C# and Java are much nicer with a little M4. Everybody loves to hate on text-substitution macros (and hey, I write parsers and such, I'm a Smug Lisp Weenie, and generally I know how easy it is to break something and how much better real macros are), but sometimes they actually are the right tool for the job. Just because they're sometimes very much the wrong tool doesn't mean they should be kept out of your toolbox. Until all languages are either Lisp-ish or Forth-ish, I will maintain that there is a place for CPP/M4/etc. :-) M4 is seriously awesome, just remember: with great text substitution comes great attention to detail. And heed the warning from the manual[1]: > Some people find m4 to be fairly addictive. They first use m4 for simple problems, then take bigger and bigger challenges, learning how to write complex sets of m4 macros along the way. Once really addicted, users pursue writing of sophisticated m4 applications even to solve simple problems, devoting more time debugging their m4 scripts than doing real work. Beware that m4 may be dangerous for the health of compulsive programmers. 1. https://www.gnu.org/software/m4/manual/m4.html https://www.gnu.org/software/m4/manual/m4.html
- generic_user 11y agoM4 is a great tool. A good chunk of programmers now seem to have never been exposed to pre processors and what you can do with them, its a shame really.
- speps 11y agoFor C# based environments, you should use T4[1] actually. It comes with Mono[2] as well as the normal CLR. It has an API and a command-line tool. [1]: https://msdn.microsoft.com/en-us/library/bb126445.aspx https://msdn.microsoft.com/en-us/library/bb126445.aspx [2]: https://github.com/mono/monodevelop/tree/master/main/src/addins/TextTemplating/TextTransform https://github.com/mono/monodevelop/tree/master/main/src/add...
- yoklov 11y agoDeferred expansion is a common (well, not that common) trick this misses that I would have included. Generally the C preprocessor is pretty terrible though, you should seriously consider generating code with an external tool before doing anything nontrivial with it. Regardless, here's a link that seems to cover this and other somewhat more obscure techniques: https://github.com/pfultz2/Cloak/wiki/C-Preprocessor-tricks,-tips,-and-idioms https://github.com/pfultz2/Cloak/wiki/C-Preprocessor-tricks,...
- dicroce 11y agoMy favorite "feature" of the pre processor is when I include Windows.h and then get a super strange compile error in my code because a macro Windows defines (with a super generic name) matches part of a name in my code (which is in a namespace btw) and expands into some unholy thing that is invisible at the source level... Fun times.
- stagger87 11y ago#undef
- fizixer 11y agoI'm desperately looking for a C preprocessor that dumps the AST (preferable in JSON format) instead of expanding the macros. And it treats the C/C++ code as just data. I plan to take the rest of the code and send it through clang to get C/C++ AST dump. Currently I'm getting clang's AST dump which "includes" all the headers and the size of the AST just blows up (e.g., 300k lines of AST for a 4k line C++ file that has about 10 include files).
- daurnimator 11y agoTry CParser: https://github.com/MatzeB/cparser https://github.com/MatzeB/cparser
- parados 11y agoTry CPIP in Python: http://cpip.sourceforge.net/ http://cpip.sourceforge.net/
- greggman 11y agoSome people hate the preprocessor. I love it. I miss it in every language that doesn't have one. I'd much rather be able to write statement statement statement #if DEBUG_FEATURE_X statement statement statement #endif statement statement statement than statement statement statement // remember to comment this code out statement statement statement // --- end of debugging code statement statement statement nor do I want a runtime check Of course ultimately I just wish C/C++ and every other language let you use the entire language at compile time like lisp (and a few others). As for more advanced macro foo macro lists are my favorite http://games.greggman.com/game/keeping_lists_in_sync_in_c__/ http://games.greggman.com/game/keeping_lists_in_sync_in_c__/ I know some people don't like them. Typically those people would solve the issue by using some other language, python, to generate C/C++. I'd prefer not to have yet another dependency.
- marvy 11y agoThere's no need to worry about a runtime check. Let DEBUG be a compile time constant, and the optimizer will remove the check. C++ seems to be (very) slowly moving in the direction of using the whole language at compile time: see how constexpr has been getting better. I doubt it will ever get anywhere near what lisp lets you do though, and in those cases the preprocessor sure does help at least partially fill the gap. This is my favorite explanation of the technique you linked to: http://journal.stuffwithstuff.com/2012/01/24/higher-order-macros-in-c/ http://journal.stuffwithstuff.com/2012/01/24/higher-order-ma...
- nkurz 11y agoLet DEBUG be a compile time constant, and the optimizer will remove the check. What do you feel is gained with "const int DEBUG" over "#define DEBUG"? While most compilers will do what you say most of the time, I haven't encountered a significant downside to the macro approach. I also like that I can have a makefile where "make debug" adds "-DDEBUG" to the compiler command line and appends "_debug" to the executable name. With the const approach, is there an easy way to automatically generate both debug and production executables?
- adenner 11y agoJust because you can doesn't mean that you should
- kbart 11y agoThat's the very basics of C preprocessor and the last part (#ifdef vs #ifs) didn't convince me at all, it's just a matter of programming style and use case.