Writing

Feed Software, technology, sysadmin war stories, and more.

Friday, January 20, 2023

Who needs main() anyway?

Want to inflict terrible things on other programmers who show up later to do maintenance work? Write C++ code that doesn't need a main(). Then write C++ code that doesn't *have* a main(). Yes.

I mentioned this quite a while back, calling it "spooky action at a distance" in code, but looking at that now, it seems like it was a very long and drawn out demonstration.

Instead, tonight, I present a far simpler version. Usual disclaimers apply: may summon Ancient Ones who will haunt your soul. Probably won't work on all systems or compilers. It didn't work for me until I gave it -O2, and even then, it still gives a magnificent segfault.

At any rate, enjoy the evil.

$ cat hhhehehehe.cc
#include <unistd.h>
 
class wat {
 public:
  wat() { write(1, "wat\n", 4); }
};
 
static wat wat_;
 
// no main.  nothing else.
$ g++ -O2 -Wall -nostartfiles -o hhhehehehe hhhehehehe.cc
/usr/bin/ld: warning: cannot find entry symbol _start; [...]
$ ./hhhehehehe 
wat
Segmentation fault
$ 

That's it.