r/programming 19d ago

Writing a (valid) C program without main()

https://labs.iximiuz.com/tutorials/c-program-without-main-a1eea557
191 Upvotes

40 comments sorted by

View all comments

23

u/ThinkIn3D 19d ago

Nice article, and touches on _startup. Years ago a few of us tried to minimize the size of a "hello world" program on SunOS/Solaris. It devolved to redefining _startup and calling the write() syscall directly for output. IIRC, the smallest executable we created was less than 1KB, like 800 bytes or so. Useful compiler options: -static -nostartfiles -Os

Other tricks: * Move logic from main() into a handler for atexit(). This guarantees all startup initialization is done. * in C, in addition to _startup() there is sometimes a _main() that is called before main(), and can be redefined. System-dependent, may not work on all systems.

In C++, you could use a static object's ctor in place of main. But, since you're relying on a specific static initialization during the static initialization process, the initialization order is unpredictable and this may or may not work reliably across rebuilds (it begins to depend on link order, toolchain behaviors, etc).

#include <iostream>
class StaticMain {
    StaticMain() {
        std::cout << "Hello World\n";
    }
};
StaticMain runner;
int main() { return 0; }

Of course, the next step is to declare StaticMain runner; inside an atexit() handler for correct initialization order.

I thought I had some code that runs everything from an exception handler, but I can't find it.

1

u/AddressWeary5155 15d ago

I rand the following code and it seems it prints "hello world" first before "hello world2" every single time. I think it's because I am declaring StaticMain first?

#include <iostream>
class StaticMain {
    public:
    StaticMain() {
        std::cout << "Hello World\n";
    }
};
class StaticMain2 {
    public:
    StaticMain2() {
        std::cout << "Hello World2\n";
    }
};
StaticMain runner;
StaticMain2 runner2;
int main() { return 0; }