Reputation: 31
Often times when I look at source code on GitHub the main
function is omitted or there is code outside of it. The tutorials I have done told me - I can do neither of these things. Is there something I am missing?
Upvotes: 1
Views: 833
Reputation: 222650
Normal complete C programs hosted in an operating system must have a main
routine.
Projects on GitHub may be mere portions of programs, such as a collection of routines intended to be used in other programs. (Such collections are often called libraries.) If source code is not intended to be a complete program by itself, then it does not need to have a main
routine. A main
routine will be added later, by somebody who uses the collection of routines in their own program.
C source code can also be compiled and used in combination with source code written in other programming languages. The behavior of this is not specified by the C standard, so it is specific to the various developer tools used when doing this. Such a hybrid program must have some main routine, but it may be called something other than main
. Nonetheless, main
has become very popular as the name of the main routine, so it is used very frequently.
C source code can be used for special software, such as operating system kernels. The C standard describes a freestanding environment, in contrast to a hosted environment. In a freestanding environment, many things are customized to the specific system, including how the starting address of the program is set. In this case, the main entry point might be called start
instead of main
, for example, and the address of that entry point might be conveyed to the hardware in some special data structure particular to the hardware.
Regarding code outside of functions, that may be initialization expressions. (There are strict limits on what expressions can be used in initialization outside of functions. You cannot write general C code in those expressions.) You would have to show specific examples to get answers about that.
Upvotes: 5
Reputation: 50099
by definition an EXECUTABBLE binary has a main method that is application's entry point.
LIBRARIES (or rather anything that doesnt need to be executable by the OS doesnt have to have a main function
so C Code itself can very well live without a main function. You cant put arbitrary code outside of a function though (be it main or otherwise) ..
generally you could say:
[thats a bit simplifed but a good rule of thumb IMO]
Upvotes: 1
Reputation: 15162
Such samples simply are not complete, for a program to work there has to be an entry point (for standard C this is main). Code statements have to be inside a function though that function need not be main.
It is, however, possible to have variables with initializers outside function bodies.
Upvotes: 0