r/ProgrammerTIL • u/finn-the-rabbit • Apr 20 '18
Other [C][C++]TIL that this actually compiles
I've known that the preprocessor was basically a copy-paste for years, but I've never thought about testing this. It was my friend's idea when he got stuck on another problem, and I was bored so:
main.cpp:
#include <iostream>
#include "main-prototype.hpp"
#include "open-brace.hpp"
#include "cout.hpp"
#include "left-shift.hpp"
#include "hello-str.hpp"
#include "left-shift.hpp"
#include "endl.hpp"
#include "semicolon.hpp"
#include "closing-brace.hpp"Will actually compile, run, and print "Hello World!!" :O
Also I just realized we forgot return 0 but TIL (:O a bonus) that that's optional in C99 and C11
main-prototype.hpp:
int main()open-brace.hpp:
{cout.hpp:
std::coutleft-shift.hpp:
<<hello-str.hpp:
"Hello World!!"endl.hpp:
std::endlsemicolon.hpp:
;closing-brace.hpp:
}
65
Upvotes
7
u/8lbIceBag Apr 20 '18
So wait, does that mean everything you include gets recompiled and duplicated? And if so, does that mean having fewer code files would reduce code size?
26
u/honeyfage Apr 20 '18
You're going to love X Macros
12
u/andural Apr 20 '18
For more fun:
http://99-bottles-of-beer.net/language-c-c++-preprocessor-115.html
4
u/derleth Apr 20 '18
Where's the C code?
2
u/Xeverous May 04 '18
Do you know it's also possible to implement a full, compile-time game?
https://github.com/mattbierner/STT-C-Compile-Time-Snake
The trick relies on Turing-completeness of C++ templates and the fact that the Snake board from previous compilation is
#included into the source code. After each compilation, the program outputs (computed at compile-time) next step of the board.The project consists of 1 source file with main and every thing else is a header.
0
u/[deleted] Apr 20 '18
[deleted] — view deleted comment