简体   繁体   中英

What really happen when I compile int main; in C

What really happen when I compile:

int main; 

Isn't it supposed to be main() and caused an error ?

I tried to compile the code in CodeBlocks and it compiled perfectly without error.

It's not an error as a C source file doesn't need to have a main function and you can define main as whatever you want as long as you don't try to define it twice in the same scope. As this is your whole program, it's fine - but the program certainly won't run correctly as there is no main function to find.

All it does is declare a global (external) variable called main, initialised to 0. The linker would normally issue an error if it's not there, but it may be satisfied with presence of the external variable (I expect it's assuming it's a pointer).

EDIT: I looked into this a little with the debugger, and sure enough, main has a value of 0, ie the variable is being used as a pointer without a cast. So the initialisation code tries to run a function located at address 0, resulting in a segfault on my platform.

I think you are getting confused here due to incorrect (or lack of understand) of the scope.

When you say here a declaration of int main; is being passed by the compiler, I am assuming you are declaring it within a function scope. But, if you try declaring it in global scope, then the compiler will throw an redefinition error.

So, as long as you don't have two identical identifiers within the same scope, compiler will be satisfied and will let you have your way.

The below code will give redeinition error:

int main;

int main()
{
  printf("In main\n");
}

The below code won't because the scope of main is restricted inside the function only and compiler considers the int main variable and result is printed out as 5.

int main()
{ 
   int main = 5;
   printf("In main, value of main is %d\n", main);
}

The below code however will print the address of main

int main()
{
       printf("In main, value of main is %d\n", main);
}

EDIT: After reading through the comments, I feel the key problem here is that you are not having a main function at all, which you should have for a "C" program to start working. If you don't have a main function, but just declare an int main; variable, your code might still compile, but when you execute there will be confusion and chaos as main is an integer variable, whereas it is expected to be a function. But, as long as you keep your main(s) under control as per my above answer, you should do fine.

You can go this link, which explains the concept of compilation and execution of a C program

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM