main function basics and C programming

A friendly reminder: main() is just a function! You can call it if you want. (But don't!) Bonus question: if you don't call main(), who does? 😉 P.S. `if(..) {...}` can be replaced with `if(putchar(*message++)) main();` for brevity and extra cringe. #CProgramming #Programming #Coding #TechHumor

  • No alternative text description for this image

The runtime. 1. The OS loader starts your program at a fixed entry point defined by the executable format. 2. The entry point is not main. It is in the C runtime (CRT) supplied by the compiler/Std Library 3. The CRT: - sets up the process (stack, environment, TLS), - initializes the C library and global/static objects, - prepares argc, argv, and envp, - then calls main(argc, argv). When main returns, the CRT: - runs cleanup/destructors, - calls exit (or equivalent), - hands control back to the OS. So if you don’t call main(), the runtime does. Bonus: The return values are stored in registers (initially). The CRT receives and passes the values from and to OS. The OS stores it as the process exit code. They can be retrieved at OS level.

I think nobody calls main(), and what is actually called is _main. Am I wrong?

Like
Reply

There are quite a few caveats with this approach, but you _can_ go like `-Wl,-e,my_entry` and bypass main, that is to say, supply another function as an entry point. Not a great idea unless you really know what you are doing.

Like
Reply

You can in C, but the C++ standard explicitly disallows it: "The function main shall not be named by an expression", https://eel.is/c++draft/basic.start.main#3

That is a ingenious Hello, world program; however, it is somewhat expensive in terms of activation frames. Albeit, it looks like it would work quite well. As long as, the "\0" is present. Even if, it is unseen. 👏

Like
Reply

Linker script, you're using by default. There's should be the name of entry point.

Like
Reply

What do you mean.. What's wrong with this! 😅

  • No alternative text description for this image
Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories