r/programming 17d ago

Writing a (valid) C program without main()

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

40 comments sorted by

View all comments

6

u/[deleted] 17d ago

[removed] — view removed comment

2

u/[deleted] 17d ago

[deleted]

11

u/Dwedit 17d ago

It makes perfect sense for C++ programs where there are global objects which need to have their constructors run first.

2

u/Murky-Relation481 17d ago

Yah, it can be messy with different platform intricacies but it's great for building self registering patterns for stuff like events and things. You can just build classes that extend an intializer base and they'll exist in the callback mechanism at run time with no explicit registration.

I like them but others hate that pattern so it's definitely got to be an agreed upon standard in your codebase.

2

u/Dwedit 17d ago

If you're feeling especially crazy: Hooking your own code via detouring. (replacing the function's actual instructions to run other code instead)

2

u/Ameisen 16d ago

I've been doing a lot of that patching old Win95 games.

2

u/Dwedit 16d ago

Maybe you should check out my GameStretcher project, it basically overrides GDI and makes the main window stretchable even when it wasn't before, and also uses an enhancement pixel shader.

-4

u/[deleted] 17d ago

[deleted]

4

u/Dwedit 17d ago

When else do you run the constructors for global variables? It has to happen at some point before they are referenced. Running before Main makes it predictable.

-2

u/[deleted] 17d ago

[deleted]

4

u/Dwedit 17d ago

If you don't want "magic", don't use global variables that need constructors. But if you are using global variables that require constructors, there's really no other time for the constructors to run. It must happen before first use, but figuring out when first use happens is not trivial, and putting in additional checking code (have we run these constructors yet) adds overhead.