tags:

views:

412

answers:

3

Hello,

I'm following this tutorial on x86 assembly. Every example so far uses what the author calls a "c-driver" program, compiled with the assembly module, for means of some "initialization". Something like:

int main(void) {
  int ret = asm_main();
  return ret;
}

And then the asm_main function is written normally, using a C calling convention. I'm wondering what exactly is the required initialization that's being generated by the C compiler, and if it can be done in a portable manner.

Infos: I'm on Windows XP, 32bit box, using the NASM assembler and mingw32-gcc for linking.

+5  A: 

The initialisation isn't generated by the c compiler, it is part of the c library (which makes it easier to tailor for each OS/processor).

The code in question is normally very simple on windows/unixy systems - typically does a bit of library initialisation (opens STDIN, STDOUT, STDERR, sets timezone etc), sets up the environment, processes the command line for passing to main; catches the return from main() and calls exit etc.

The start up code in most c libraries is in a file called crt0.c, crt1.c or something similar (crt = c run time).

On more primitive or bare systems it will also set up the stack and other registers and clear the BSS data area - in this case it would often be in assembler (typically crt0.S).

Here is a link to the BSD c startup code - link text

And the start up code for mingw for windows is in crt1.c here - http://mingw.cvs.sourceforge.net/viewvc/mingw/runtime/

Dipstick
In a C project, all these setups you talk about are handled automagically before main is called (and exit things happen automagically after main returns).Now you may ask, "what is a C project?". Well, that's a bit of a sticky question, but basically if you have a "main" function and link with libc (-lc) you are working as a C project even if every function in your code is written in asm.
Southern Hospitality
A: 

You could write your main in assembly if you want. But a lot of people want to put debugging statements in the main and those are easier in C than in asm.

If you wrote main in asm you might have to deal with main actually being called _main or using an alternate calling convention (especially under Windows) or other strange things like that that the C compiler handles for you automatically when generating code for a function with the name "main". This way makes it so you don't have to do that either.

Southern Hospitality
A: 

The stack, registers, and program's file sections (data, rodata, bss, etc) have to be initialized before main() is called. C runtime library (CRT) provides this initialzsation.

CRT also provides prologue and epilogue code that is executed before and after each function is called. The prologue and epilogue code updates the stack and frame pointers.

terry