Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to write a program without using main() function?

I keep getting this question asked in interviews:

Write a program without using main() function?

One of my friends showed me some code using Macros, but i could not understand it.

So the question is:

Is it really possible to write and compile a program without main()?

like image 559
Expert Novice Avatar asked Aug 13 '11 14:08

Expert Novice


1 Answers

No you cannot unless you are writing a program in a freestanding environment (embedded environment OS kernel etc.) where the starting point need not be main(). As per the C++ standard main() is the starting point of any program in a hosted environment.

As per the:

C++03 standard 3.6.1 Main function

1 A program shall contain a global function called main, which is the designated start of the program. It is implementation-defined whether a program in a freestanding environment is required to define a main function. [ Note: In a freestanding environment, start-up and termination is implementation-defined; startup contains the execution of constructors for objects of namespace scope with static storage duration; termination contains the execution of destructors for objects with static storage duration.


What is freestanding Environment & What is Hosted Environment?
There are two kinds of conforming implementations defined in the C++ standard; hosted and freestanding.

A freestanding implementation is one that is designed for programs that are executed without the benefit of an operating system.
For Ex: An OS kernel or Embedded environment would be a freestanding environment.

A program using the facilities of an operating system would normally be in a hosted implementation.

From the C++03 Standard Section 1.4/7:

A freestanding implementation is one in which execution may take place without the benefit of an operating system, and has an implementation-defined set of libraries that includes certain language-support libraries.

Further,
Section: 17.4.1.3.2 Freestanding implementations quotes:

A freestanding implementation has an implementation-defined set of headers. This set shall include at least the following headers, as shown in Table:

18.1 Types <cstddef>    18.2 Implementation properties <limits>    18.3 Start and termination <cstdlib>  18.4 Dynamic memory management <new>  18.5 Type identification <typeinfo>  18.6 Exception handling <exception>  18.7 Other runtime support <cstdarg> 
like image 122
Alok Save Avatar answered Oct 14 '22 07:10

Alok Save