Search code examples
ccompilationprogram-entry-point

How to compile and run `main;` in C


main;

This is the smallest program that can be compiled in C. Compilation warnings (gcc):

test.c:1:1: warning: type defaults to ‘int’ in declaration of ‘main’ [-Wimplicit-int]
test.c:1:1: warning: ‘main’ is usually a function [-Wmain]

I'd like to understand what it means, syntactically speaking, namely:

  • why the semicolon when declaring a function ?
  • why are the missing parenthesis and curly brackets legal ?

I know that the default return type of a function is int when omitted. I also heard of the _start function which is called before main. This would mean that it is calling a function that hasn't been defined(?).

Why exactly does the executable segfaults when run ?


Solution

  • Because you didn't specify a type for main, the compiler is defaulting to a type of int. Not a function returning an int, but an int. This is legal from a syntactic standpoint, as you could have also had myvar; in your code which would also be declared as int.

    But because main is special, that's why you get the second warning. It is letting you know that how you defined main differs from what how it is typically defined.

    So when you compile this program an attempt to run it, it is expecting main to be the start of a function when it is actually just an int variable. This is what causes the segfault.