13 ms·
Is the C++ preprocessor still needed?
- frozenport 10y agoModules change the behavior of includes
- astrodust 10y agoModules are massively over-due. A faster pre-processor processor wouldn't hurt either.
- CyberDildonics 10y agoFaster pre-processor? What makes you think that is the bottleneck? tcc can fully compile all 6MB of sqlite in 1/100th of a second.
- pjmlp 10y agoAnd the performance of the generated executable is....
- CyberDildonics 10y agoI don't think you've understood. If it can compile the whole program, that means it must have ran the preproccesor. If it can run the preproccesor on 6MB of C in 1/100th of a second, a faster preproccesor is not going to do much for compile times since it isn't the bottleneck.
- pjmlp 10y agoYeah, I misunderstood you. You are right.
- astrodust 10y agoSQLite is C, and C header files tend to be trivial in comparison to their template-loaded C++ counterparts. Even though Firefox is only a few orders of magnitude bigger in terms of source code it takes exponentially longer still to compile.
- CyberDildonics 10y agoAnd you think the preproccesor is a bottleneck in C++ ?
- mabynogy 10y agoI use the gcc preprocessor in Javascript (to avoid modules and tools like browserify): out="out/make1.js" main="make1/main.js" gcc -C -E -H -P -nostdinc -undef -x c $main -o $out node --harmony $out $@
- kevin_thibedeau 10y agoYou would be better served with m4.
- flukus 10y agoI looked into m4 recently but it seems to be about the worst template engine imaginable. I'd take the c pre-processor over that any day. In the end I opted for a sed/awk/cat combo instead.
- daxelrod 10y agoCould you please point to some good m4 learning and reference resources? The only time I had to write m4 was admittedly in the context of autotools, but I found it really difficult to get answers to my questions about how everything worked.
- s_kilk 10y agoI wrote up a little tutorial on using m4 as a CSS pre-processor: http://blog.00null.net/post/144763147991/use-the-unix-m4-as-a-css-pre-processor http://blog.00null.net/post/144763147991/use-the-unix-m4-as-...
- flukus 10y agoWow thanks, that's a much better intro to the ones I cam across like this (http://mbreen.com/m4.html http://mbreen.com/m4.html). I may have to reevaluate it.
- daxelrod 10y agoCould you please point to some good m4 learning and reference resources? The only time I had to write m4 was admittedly in the context of autotools, but I found it really difficult to get answers to my questions about how everything worked.
- jimjimjim 10y agooh god, please don't add more stuff to the language.
- goalieca 10y agoSince c++11 I can't think of an enhancement that hasn't been beneficial.
- EGreg 10y agoLambdas. Concepts. Ten types of casts. Templates of templates. Everything and the kitchen sink is in there. You need a language lawyer to figure out anything but the most basic interactions. For example, 1. What's the practical difference between an abstract class and an interface? 2. When do you have a copy constructor run instead of a cast on initialization if both are defined? 3. When would you use a non-virtual destructor? What happens when you hire people? Isn't it better to have a small language that everyone understands in its entirety, and has to go out of their way to surprise you?
- wfunction 10y ago> 1. What's the practical difference between an abstract class and an interface? Interface? You are talking about the C++ language, right?
- kobeya 10y agoThe funny thing is I just good faith assumed that this was some new feature being added in C++17 that I'd now have to figure out how to use.
- santaclaus 10y ago> Interface? You are talking about the C++ language, right? If Sutter's metaclasses get into C++20 C++ could indeed have an equivalent to interface enforced by the compiler.
- Ace17 10y ago
- codemac 10y agoThe year is 2017 - is anyone worried about the preprocessor? I feel it's largely worked out, and is well understood.
- codemac 10y agoThe year is 2017 - is anyone worried about the preprocessor? I feel it's largely worked out, and is well understood. I
- partycoder 10y agoYou would break many libraries starting by boost.
- jordigh 10y agoI have to comment on this, even though it's almost completely irrelevant to the blog post. I saw "do_sth" so I wanted to check where the writer was from. Germany. Aha. :-) I love how reliably abbreviating "something" (e.g. "sth", "smth" or "sthg") indicates that the person isn't from an English-speaking country. I wonder why this abbreviation has never caught on in English-speaking countries. I think the abbreviations got popularised in non-English-speaking countries by English dictionaries. I think the more common idiomatic "abbreviation" would be "do_stuff" when you don't want to type out or say "something".
- nscalf 10y agoI'm sure it's not valid across the board, but most of the internet shortenings that we use in english are acronyms---lol, stfu, wtf, rofl, hbu, asl, etc. I'm actually having a hard time thinking of some common abbreviations. I guess "func" short for "function" is a common example.
- dyarosla 10y agoProgramming has plenty of common abbreviations: obj, str, char, btn
- Jach 10y agoPlus old programmers had to pay a heavy vowel tax so many, even unnecessary, abbreviations stick with us. I worked with an older guy on a game once, "extern struct CollisionManager g_clisn_mngr" is an example of the sort of things we did...
- deleted 10y ago[deleted]
- kobeya 10y agoBecause as you point out yourself, there really is no need for that abbreviation. You could say "do_stuff" and it would have approximately the same meaning, but not be an undecipherable, ambiguous abbreviation.
- nachexnachex 10y agoC coder here (former pre-C++11 C++ as well). Another point to mention (which I think adds to the conclusion) is that by losing compatibility with the C preprocessor you'd lose compatibility with, well, C. This means breaking of both C++ code that uses C libraries legitimately and "C++" code that's actually C with new/delete (or "the horror" as we put it).
- paulddraper 10y agoTrue, and the worth remembering. If you did want to do this, you'd run a C processor on the C code first.
- DSMan195276 10y agoI would also add that when you're doing low-level work that requires mixing a bit of assembly and C (Or C++, but I mainly stick to C), being able to access the preprocessor from assembly is really nice. The alternative is redefining tons of stuff so you can use it in your assembly. It's a niche use-case obviously, but it is still a nice use-case regardless and I'd wager you could do this with lots of other languages if you ever had a want/need.
- deleted 10y ago[deleted]
- pjmlp 10y ago> by losing compatibility with the C preprocessor you'd lose compatibility with, well, C. Thankfully C++ no longer needs it to gain market share, it can stand on its own, while cleaning up the warts that caused unsafe code as a means of getting adopted.
- qb45 10y agoHa ha ha, #ifdef __cplusplus extern "C" { #endif I guess you will have to rewrite libc.so and ntdll.dll in C++ first. Or at least fork them and maintain the fork indefinitely.
- 10y ago
- surrey-fringe 10y agohttps://en.wikipedia.org/wiki/Betteridge%27s_law_of_headlines https://en.wikipedia.org/wiki/Betteridge%27s_law_of_headline...
- gjm11 10y agoI think a more accurate version of Betteridge's law says: when a headline asks a question, the answer is always the less surprising answer. It just happens that usually the more attention-grabbing way to write the headline is the one that makes "no" the less surprising answer. The Betteridge-compliant version of this article would have been titled "Can we do without the C++ preprocessor?".
- surrey-fringe 10y agoThat's the joke. Made me laugh anyway.
- deleted 10y ago[deleted]
- throwaway200905 10y agoI mean no offence but looking on what this guy says he's probably never worked a paid C++ job and it looks like he will never be.
- Jimmy 10y agoIf you want to keep compiling any existing C++ code, then the answer is "yes".
- hossbeast 10y agoAfter reading about all the hoops the author is willing to jump through to avoid using the preprocessor, I was expecting the conclusion to be, yes, it turns out we still need it.
- foonathan 10y agoThe conclusion is "yes, we still need it".
- yongjik 10y ago> The function std::experimental::source_location::current() expands to the information about the source file at the point of writing it. Hmm, okay, and what happens when someone puts that thing in a macro? Some macros can be horribly ugly, but I'm not sure replacing __FILE__ with compiler-supported magic is an improvement.
- WalterBright 10y ago> replacing __FILE__ with compiler-supported magic D doesn't have a preprocessor, and so that's just what it does: http://dlang.org/spec/traits.html#specialkeywords http://dlang.org/spec/traits.html#specialkeywords
- gpderetta 10y agoThe use case for source_location is as a default value of a (function or template) parameter. BTW, __FILE__ is compiler supported magic (well, preprocessor, but they are the same thing).
- deleted 10y ago[deleted]
- tunnuz 10y agoAlso, with #pragma once (practically supported by every compiler toolchain) we don't need to do the if-not-defined-include trick.
- llukas 10y agoNot if you do embedded.
- CamperBob2 10y agoWhat does "embedded" have to do with anything? #pragma once works fine in gcc-arm-none-eabi.
- fnj 10y agoI think he means you may not have #pragma once available in every embedded compiler. Embedded compilers are a mixed bag; gcc is a standout.
- llukas 10y agoYes there is world out there outside of gcc sphere ;)
- com2kid 10y agoEven ARM's embedded cortex-m compilers have supported #pragma once for years now. Maybe some of the 8-bit micros still don't..?
- fnj 10y agoDidn't you ever have to program a Persistor 68332 with an ancient version of CodeWarrior? How about CCS C for the 18F PIC?
- com2kid 9y agoThankfully no, M0s nearly come in cracker jack boxes now days. A lot of what used to be on 8bits are moving to M0s because why the heck not. Commercially advertised prices are around 60 cents in bulk, corporate buys in the 100s of thousands are going to be cheaper than that. Death to 8bits! :)
- lacampbell 10y agoWell until C++ develops an implementation of schemes syntax-rules - I hope it stays.
- Stenzel 10y agoI am missing the motivation to purge the preprocessor - only reason he gives is the paradigm that the preprocessor is considered bad practice. I fail to see why. The preprocessor is a useful tool that can save you time and make code more readable and portable. Conditions at compile time guarantee that the compiler is not subjected to a specific portion of code, and it offers the only way to define a constant value without having an implicit type for that. Considering the use of C/C++ outside pure computer programming, like embedded systems or digital signal processing, where portability, code size and target specific substitutions or optimisations matter, there is simply no reason and no way to get rid of the preprocessor without breaking things. Sure you can use it in obscure and wrong ways, but it is not the job of the language to act as a nanny and prevent you from doing evil by restricting access to dangerous toys.
- qb45 10y agoCPP is not without warts. It complicates static analysis (machine and human), for one thing. You need the definition of variable foo or function bar? Great, which one? Who made the last assignment to foo and what its value could be? Does this ifdefed snippet here count?
- tomsmeding 10y agoIt is also not without very legitimate uses. Feel free to not use the preprocessor if you don't want (you're still using it with `#include` though), but it is very useful for specific use cases, and there is no real reason to remove support for it.
- foonathan 10y agoAuthor here, I didn't intend to give a motivation for purging it, many people in the C++ community want to and I wanted to explore the feasibility of that in the current status. > like embedded systems or digital signal processing, where portability, code size and target specific substitutions or optimisations matter, there is simply no reason and no way to get rid of the preprocessor without breaking things. It certainly is, I know embedded projects where they use template meta programming to get an even more advanced code generator.
- Taniwha 10y agoThe thing is all people don't use C++ the same way - I've often found myself using a small amount of C++ mixed with large amounts of C written by others - my use of C++ needs to live with other's C headers, their #defines and #includes - my use of C++ is no more or less valid than your's BTW cpp is not slow, not compared with other parts of C++ compilers
- qb45 10y ago> don’t use it for inline functions That's a myth afaik. Is there any standard way besides macros to really ensure the code will be inlined? In particular, the suggestively named inline keyword just doesn't work like that.
- foonathan 10y agoThere are attributes like `[[gnu::always_inline]]` for GCC and clang.
- qb45 10y agoYes, but they aren't portable. You can work around this using per-compiler macros, which I guess is another reason why CPP is to stay.
- ChrisFoster 10y agoThe preprocessor is a workable but somewhat poor tool for inlining code due to several reasons (no overloading, no sensible macro scoping, template argument lists clash with macro argument lists, etc). However, it's quite a reasonable tool for helping to force inline code in a nonstandard but somewhat portable way. See, for example, EIGEN_ALWAYS_INLINE at https://eigen.tuxfamily.org/dox/Macros_8h_source.html https://eigen.tuxfamily.org/dox/Macros_8h_source.html
- smitherfield 10y agoSticking with stuff that's in the standard, "constexpr" is, among other things, a more strongly-suggested "inline". Also, inlining is likely if you compile with -02/-03 and declare the function with internal visibility (in an anonymous namespace or with "static", although the latter is deprecated in favor of the former in C++).
- rwmj 10y agoOCaml doesn't have a C-style preprocessor, but I sometimes wish it did have one. One case is where a function has changed its type signature, eg. adding a parameter, but you still want to be able to write code that can compile with the old and new versions of the library. It would be quickest to write: #if HAVE_OLD_LIB f 1 2; #else f 1 2 3; #endif The actual solution in pure OCaml is a huge pain. Usually you have to add another module which is conditionally compiled. Luckily in OCaml you can write ‘ocamlopt -pp cpp’ to use the C preprocessor on selected files.
- mailslot 10y agoYes, but I don't know if you're talking about the C++ (templates and constexpr's & whatnot) or the C preprocessor. Macros? Get rid of those and you kill my logging solution.
- daemin 10y agoI'm wondering if anyone has tried to use another language - I'm thinking Ruby - as a pre-processor for C++ code. I know people have pre-processed C++ code with various tools - for example Qt - but I'm thinking of just replacing # pre-processor statements with something like Rails based templates.
- AlbertoGP 10y agoI used Python to generate C++ with a utility I wrote called "PythonPP": http://matracas.org/utiles/index.html.en http://matracas.org/utiles/index.html.en One of the things it did was to generate the function prototypes so that a typical .h file would look like this: #!from base_cc import * #""// Clase: ${project_part_name} #""// Proyecto: ${project_name} #!import time #""// Fecha: ${time.strftime("%A, %d de %B de %Y, %H:%M:%S %Z", time.localtime(time.time()))} #""${cc_copyright_notice("GPL", "2001, 2002, 2003, 2007, 2010")} #""#ifndef _H_${project_part_name} #""#define _H_${project_part_name} #""${cc_function_includes_for_class()} #""${cc_variable_global_declarations_for_class()} #""class ${project_part_name} { #""${cc_variable_declarations_for_class()} #""${cc_function_protos_for_class()} }; #""${cc_operator_protos_for_class()} #endif The .cc file was similar, calling Python functions to get the function definitions from separate files: I built one directory for each class, where I would put each big function or several related small functions in its own file, and they would be found and combined automatically. For each class, there was a vars.cc file which contained member variables, with their declaration line, initialization and destruction in consecutive lines: the declaration went to the .h file, the initialization to the constructor, and the destruction to the destructor. This way I avoided forgetting to release something and had a good overview of all variables and their life cycles. Here is an example of generating constant names from a Python list: #!for token_id in lexer_table: #" " case TOKEN_ID_${token_id[1]}: #' ' cerr << "\n --- [" << index_of_current_character #" " << "] TOKEN_ID_${token_id[1]} '" << buffer << "'" #' ' << endl << flush; #' ' break; The same idea was also used in the Bison/Yacc grammar file: #!%token <markup> T_QMATH_DIRECTIVE %token <markup> T_DIRECTIVE_DEFINITION %token <markup> T_DIRECTIVE_CONTEXT for d in qmath_directives: #" "%token <markup> T_DIRECTIVE_${d.upper()} I've used it also for other languages like Java where it cuts down the boilerplate. For instance, the package names are automatically generated from the file path.
- flamedoge 10y agosometimes I'd use C macro just because it's so darn hard to write capturing lambda code in C++. But capture lambda is suppose to be better and safer. I should use it more.
- Const-me 10y agoWhen I do that, I just type [](){} first, then start filling whatever I need in between those things.
- pantalaimon 10y agoWhen I read things like https://twitter.com/sebrose/status/858347156427636738 https://twitter.com/sebrose/status/858347156427636738 I wonder two things. - What does that even mean? - Why is this needed when I can do well without all that in C?
- Const-me 10y agoA code that runs at compile-time, and verifies some restrictions about classes. Namely, this one implements a class called “interface” so you can create your stuff based on that, and verifies that your interfaces don’t contain any data members or non-public functions. It’s useless for me as well, but for different reason. I code for Windows, and Microsoft’s compiler has __interface keyword for decades: https://msdn.microsoft.com/en-us/library/50h7kwtb.aspx https://msdn.microsoft.com/en-us/library/50h7kwtb.aspx
- ericfrederich 10y agoDeprecate it now and it'll disappear in 20 years. If CopperSpice was able to do it with a project as big as Qt it should be possible for any project. http://www.copperspice.com/presentations.html http://www.copperspice.com/presentations.html