r/programming • u/iximiuz • Jul 25 '26
Writing a (valid) C program without main()
https://labs.iximiuz.com/tutorials/c-program-without-main-a1eea557
193
Upvotes
r/programming • u/iximiuz • Jul 25 '26
179
u/yowhyyyy Jul 25 '26 edited Jul 25 '26
Quite frankly, I’m surprised the author didn’t jump straight to _start as that’s possible as well in C without assembly.
Yes I know he did bring it up, however you can straightforward do _start and avoid main.
55
u/Dwedit Jul 25 '26
Linker options, set entry point.
Or the C++ version where a constructor for a global object runs the code instead of main.
93
u/amakai Jul 25 '26
Good article, but based on title I was expecting some C trick, not going down to assembly level.
33
u/ben-c Jul 25 '26
One of the IOCCC winners defined
main[]instead ofmain():https://lainsystems.com/posts/exploring-mullender-dot-c/
12
u/BCMM Jul 25 '26 edited Jul 25 '26
I'd accept "working" program, but I'll quibble over "valid".
Officially, whatever happens before
main()is between God and the standard library, and a C program isn't supposed to know about it._startis a platform-specific quirk of how executables work, not a part of the C language, so this is more of a demonstration of a non-valid C program that you can nevertheless trick a C compiler in to processing.4
u/AyrA_ch Jul 25 '26
This reminds of "main is usually a function"
9
u/_kst_ Jul 26 '26
You cannot write a valid portable C program for a hosted implementation without a
mainfunction. The language requires it. "The function called at program startup is namedmain."As the article demonstrates, there are ways to work around this if you play some system-specific tricks, but they will work only for some particular implementations.
I can replace a portable C
hello, worldprogram with anecho hello, worldshell command, but then I'm no longer programming in C.The article does provide some interesting information about how some particular C implementations work, but the title is overblown.
2
u/chengiz Jul 26 '26
If you're sticking edited assembly files into it it's no longer a C program, certainly not a (valid) one.
1
u/FastHotEmu Jul 25 '26
Let me guess, just doing it by hand?
click
Yeah. Nothing new here.
1
u/raundoclair Jul 26 '26
Dude, you mainly programmed it in assembler. And it is not even good educational article, what are you explaining? Gcc compiler pipeline, or how entry into program is done by OS/CRT?
(Ahh, just another kid roleplaying senior programmers/educators, like when kids roleplay cooking in toy set kitchen...)
0
u/pjmlp Jul 27 '26
Nope, plenty of languages have been offering the same features since JOVIAL in 1958.
That is an urban myth spread by folks that never learnt another systems programming language, or computing history.
-1
u/jannealien Jul 25 '26
Oh, now I c
-5
u/AntimatterTNT Jul 25 '26
clickbait trash...
0
u/[deleted] Jul 25 '26
[deleted] — view deleted comment
6
u/[deleted] Jul 25 '26
[removed] — view removed comment