39

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()?

Alok Save
  • 202,538
  • 53
  • 430
  • 533
Expert Novice
  • 1,943
  • 4
  • 22
  • 47
  • 15
    Seems like a pretty stupid interview question... Maybe you forgot about some detail? – Gabriel Ščerbák Aug 13 '11 at 14:20
  • 4
    Don't you just love these practical interview questions? /sarcasm – Peter Alexander Aug 13 '11 at 14:20
  • 5
    How exactly does this show whether the candidate can solve problems or fit in? It's hard enough to write and maintain readable programs, why ask about such abominations? Unless the company is called IOCCC, that is. – Omri Barel Aug 13 '11 at 14:29
  • It depends what they mean. Did they mean "with no main() function"? or did they mean "Run code without running it from main (even indirectly)"? – Martin York Aug 13 '11 at 16:10
  • "Keep getting asked"? What, did some list titled "TEH BESTEST C+ Interview Questions" just get posted on the interweb? Where are you located? With whom are you interviewing? Because I want to run in the other direction. My suggestion is that if someone asks you this question, you eliminate *them*. And BTW, the answer is "yes", you can "write and compile" such a program, you just cannot successfully link it (at least on a standard, hosted, compliant system). I might be splitting hairs, but that would be my smart-ass response if I was asked the question. – Dan Aug 13 '11 at 20:58

22 Answers22

30

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>
asthasr
  • 9,125
  • 1
  • 29
  • 43
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • Are you sure? I mean everyone writing an OS kernel or embedded programs will have to do without a main function and I'd hope that such a thing wouldn't result in undefined behavior. – Voo Aug 13 '11 at 14:54
  • It seems weird to me that first you say "No you cannot." but then you quote the spec where it says that sometimes you may omit defining it. – Johannes Schaub - litb Aug 13 '11 at 14:55
  • @ Johannes Schaub - litb: Ah, I will add the exception of freestanding environments. – Alok Save Aug 13 '11 at 14:58
  • @Voo: No freestanding environments like embedded programs or OS kernels can omit the `main`, check the quote from the standard. – Alok Save Aug 13 '11 at 15:03
20

Within standard C++ a main function is required, so the question does not make sense for standard C++.

Outside of standard C++ you can for example write a Windows specific program and use one of Microsoft's custom startup functions (wMain, winMain, wWinmain). In Windows you can also write the program as a DLL and use rundll32 to run it.

Apart from that you can make your own little runtime library. At one time that was a common sport.

Finally, you can get clever and retort that according to the standard's ODR rule main isn't "used", so any program qualifies. Bah! Although unless the interviewers have unusual good sense of humor (and they wouldn't have asked the question if they had) they'll not think that that's a good answer.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • Oh. I'd planned to just let this answer B, with mistake for all 2 C. (OK, just watched Star Wars movie). It was complemented and corrected by e.g. [Als' answer](http://stackoverflow.com/questions/7050925/is-it-possible-to-write-a-program-without-using-main-function/7050940#7050940) and [Johannes Schaub's answer](http://stackoverflow.com/questions/7050925/is-it-possible-to-write-a-program-without-using-main-function/7051154#7051154). Now, in case a causal later reader doesn't see it: a **frestanding environment**, e.g. such as a compiler for a DSP, allows other startup function than `main`. – Cheers and hth. - Alf Aug 13 '11 at 22:20
  • 1
    @anonymous downvoter: please explain your reasons for downvoting, so that others may benefit from your insight(s). – Cheers and hth. - Alf Aug 14 '11 at 02:46
  • 3
    I'm not the anonymous downvoter - but I suspect its a vote against this being the accepted answer, when it is not accurate. Its a really poor interview question - but this answer is misleading as it is only true for the (admittedly more common) hosted environment. – iandotkelly Aug 15 '11 at 00:56
16

Sample program without a visible main function.

/* 
    7050925.c 
    $ gcc -o 7050925 7050925.c
*/

#include <stdio.h>
#define decode(s,t,u,m,p,e,d) m##s##u##t
#define begin decode(a,n,i,m,a,t,e)

int begin()
{
        printf("How mainless!\n");
}

From: http://learnhacking.in/c-program-without-main-function/

miku
  • 181,842
  • 47
  • 306
  • 310
  • 5
    Actually, [this](http://www.ideone.com/m1sOZ) is as good as `#define begin() main()`, You can just add a lot of lesser known/popular C/C++ constructs and mask it but the main has to be defined for a hosted environment implementation,Adding this comment here because without this the answer might be little misleading to newbies. – Alok Save Aug 13 '11 at 16:23
  • 7
    This code is not without main. `gcc -E file.c` would give you the code which is actually being compiled. – phoxis Aug 14 '11 at 04:03
11

main means an entry point, a point from which your code will start executing. although main is not the first function to run. There are some more code which runs before main and prepares the environment to make your code run. This code then calls main . You can change the name of the main function by recompiling the code of the startup file crt0.c and changing the name of the main function. Or you can do the following:

#include <stdio.h>

extern void _exit (register int code);

_start()
{
  int retval;
  retval = my_main ();
  _exit(retval);
}

int my_main(void)
{
  printf("Hello\n");
  return 0;
}

Compile the code with:

gcc -o no_main no_main.c -nostartfiles

The -nostartfiles will not include the default startup file. You point to the main entry file with the _start .

main is nothing but a predefined entrypoint for the user code. Therefore you can name it whatever, but at the end of the day you do need an entry point. In C/C++ and other languages the name is selected as main if you make another language or hack the sources of these language compilers then you can change the name of main to pain but it will bring pain, as it will violate the standards.

But manipulating the entry function name is useful for kernel code, the first function to run in the kernel, or code written for embedded systems.

phoxis
  • 60,131
  • 14
  • 81
  • 117
8

They may refer to a program written for a freestanding implementation. The C++ Standard defines two sorts of implementations. One is a hosted implementation. Programs written for those implementations are required to have a main function. But otherwise, no main function is required if the freestanding implementation doesn't require one. This is useful for operation system kernels or embedded system programs that don't run under an operation system.

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
7

Yes

$ cat > hwa.S
write = 0x04
exit  = 0xfc
.text
_start:
        movl    $1, %ebx
        lea     str, %ecx
        movl    $len, %edx
        movl    $write, %eax
        int     $0x80
        xorl    %ebx, %ebx
        movl    $exit, %eax
        int     $0x80
.data
str:    .ascii "Hello, world!\n"
len = . -str
.globl  _start
$ as -o hwa.o hwa.S
$ ld hwa.o
$ ./a.out
Hello, world!

The kernel that really runs an executable knows nothing about internal symbols, it just transfers to an entry point specified in binary in the executable image header.

The reason you need a main is because normally your "main program" is really just another module. The entry point is in library-provided startup code written in some combination of C and assembly and that library code just happens to call main so you normally need to provide one. But run the linker directly and you don't.

To include a C module1...

Mac:~/so$ cat > nomain.S
.text
.globl start
start:
        call   _notmain
Mac:~/so$ as -o nomain.o nomain.S
Mac:~/so$ cat > notmain.c
#include <unistd.h>

void notmain(void) {
  write(1, "hi\n", 3);
  _exit(0);
}
Mac:~/so$ cc -c notmain.c
Mac:~/so$ ld -w nomain.o notmain.o -lc
Mac:~/so$ ./a.out
hi


1. And I'm also switching to x86-64 here.
DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
6

Yes it possible to compile with out main but you cannot pass the linking phase though.

 g++ -c noMain.cpp -o noMain.o
Mahesh
  • 34,573
  • 20
  • 89
  • 115
3

As long as you are using g++ you could change your entry point with linker option -e, so the following code and compile command may let you create a program without a main() function:

#import <iostream>

class NoMain
{
public:
    NoMain()
    {
        std::cout << "Hello World!" << std::endl;
        exit(0);
    }
} mainClass;

I gave file name as noname.cpp, and the compile option is:

g++ nomain.cpp -Wl,-e,_mainClass -v

To tell the truth, I didn't fully understand why the code can works fine. I suspect that the address of global variable mainClass is the same to constructor of NoMain class. However, I also have several reasons that I could tell my guess may not correct.

Joohae Kim
  • 41
  • 4
3

"Without using main" might also mean that no logic is allowed within main, but the main itself exists. I can imagine the question had this cleared out, but since it's not cleared here, this is another possible answer:

struct MainSub
{
   MainSub()
   {
      // do some stuff
   }
};

MainSub mainSub;

int main(int argc, char *argv[]) { return 0; }

What will happen here is that the stuff in MainSub's constructor will execute before the unusable main is executed, and you can place the program's logic there. This of course requires C++, and not C (also not clear from the question).

Eran
  • 21,632
  • 6
  • 56
  • 89
  • Why would `MainSub::MainSub()` be executed? You don't construct a MainSub object anywhere? – Dan Aug 13 '11 at 15:37
  • 1
    @Dan, yes I do. Right below the struct's definition, and above `int main`. – Eran Aug 13 '11 at 15:42
  • Oh right, I thought that would be just a declaration. If it were a primitive i.e. `int`, its value would be undefined, no? – Dan Aug 13 '11 at 15:45
  • 1
    @Dan, if it were an `int`, it would have been [initialized to 0](http://stackoverflow.com/questions/60653/is-global-memory-initialized-in-c). – Eran Aug 13 '11 at 15:55
  • You learn something new about C++ all the time. I never knew that... though I did have to test it ;) +1 for teaching me something new. – Dan Aug 13 '11 at 16:01
2

I think the macro reference was to renaming the main function, the following is not my code, and demonstrates this. The compiler still sees a main function though, but technically there's no main from a source point of view. I got it here http://www.exforsys.com/forum/c-and-c/96849-without-main-function-how-post412181.html#post412181

#include<stdio.h>
#define decode(s,t,u,m,p,e,d) m##s##u##t
#define begin decode(a,n,i,m,a,t,e)

int begin()
{
  printf(" hello ");
}
1

Write a class and print your name in the constructor of that class and declare a GLOBAL OBJECT of that class. So the class' constructor gets executed before main. So you can leave the main empty and still print your name.

class MyClass
{
   myClass()
   {
       cout << "printing my name..." <<endl;
   }
};

MyClass gObj; // this will trigger the constructor.

int main()
{
   // nothing here...
}
1

I realize this is an old question, but I just found this out and had to share. It will probably not work with all linkers, but it's at least possible to trick ld (I'm running version 2.24.51.20140918) into thinking there is a main-function by doing this:

int main[] {};

or even just

int main;

You can then apply one of the aforementioned tricks to let the program execute some code, e.g. through the use of a constructor:

struct Main
{
    Main()
    {
        cout << "Hello World!\n";
        exit(0);
    }
} main_;

The exit(0) is to prevent the array from being "called". Good fun :-)

JorenHeit
  • 3,877
  • 2
  • 22
  • 28
1

Yes you can do it by changing the entry point of the C language from main() to _start Here is the code :

#include<stdio.h>
#include<stdlib.h>
int sid()
{
printf("Hallo World\n");
exit(0);
}

Then run the code using gcc complier.Let's assume that you have saved the file with the name of test.c then.

gcc -nostartfiles test.c
./a.out
CreatorGhost
  • 327
  • 4
  • 7
1

Disregarding specific language standards, most linking loader provides some means to declare a function name (entry point) which must be executed when the binary is loaded is loaded into memory.

For old school c language, default was something like 'start' or '_start', defined in so-called crt (c runtime?), which does several householding jobs needed for c standard functions, such as preparing memory heap, initialising static variable areas, parsing command line into argc/argv, etc.

Possibly you could override the entry point function if you take enough care not to use the standard functions which requires those household things (e.g. malloc(), free(), printf(), any class definitions have custom constructor, ...) Quite restrictive but not impossible if you use functions provided by o/s, not by standard c runtime.

For example, you can make a simple helloworld using write() function on descriptor 1.

shr
  • 525
  • 4
  • 7
1

When C or C++ code runs, it executes at a known start address, the code here initialises the run-time environment, initialises the stack pointer, performs data initialisation, calls static constructors, then jumps to main().

The code that does this is linked with your code at build time by the linker. In GCC it is usually in crt0.s, with a commercial compiler it is unlikely that this code will be available to you.

In the end, it has to start somewhere and main() is just a symbolic name for that location. It is specified by the language standard so that developers know what to call it, otherwise code would not be portable from one tool chain to another.

If you are writing code for a 'bare-metal' system with no OS or at least no OS in the sense of a process loader (embedded systems often include an RTOS kernel that is started after main()) , then you can in theory call the C code entry point whatever you wish since you usually have complete control over run-time start-up code. But do do so would be foolish and somewhat perverse.

Some RTOS environments such as VxWorks, and most application frameworks in general include main() )or its equivalent) within their own library code so that it runs before the user application code. For example VxWorks applications start from usrAppInit(), and Win32 applications start from WinMain().

Clifford
  • 88,407
  • 13
  • 85
  • 165
0

1) Using a macro that defines main

#include<stdio.h>
#define fun main
int fun(void)
{
printf("stackoverfow");
return 0;
}

Output:

stackoverflow

2) Using Token-Pasting Operator The above solution has word ‘main’ in it. If we are not allowed to even write main, we ca use token-pasting operator (see this for details)

#include<stdio.h>
#define fun m##a##i##n
int fun()
{
printf("stackoverflow");
return 0;
}
Anshuman Singh
  • 1,134
  • 1
  • 13
  • 21
0

yes it is possible to write a program without main().

But it uses main() indirectly.

following program will help you to understand..

#include<stdio.h>
#define decode(s,t,u,m,p,e,d) m##s##u##t
#define begin decode(a,n,i,m,a,r,e)
int begin()
{
printf(” you are inside main() which is hidden“);
}

The ‘##‘ operator is called the token pasting or token merging operator. That is we can merge two or more characters with it.

In the 2nd line of the program-

define decode(s,t,u,m,p,e,d) m##s##u##t

What is the preprocessor doing here. The macro decode(s,t,u,m,p,e,d) is being expanded as “msut” (The ## operator merges m,s,u & t into msut). The logic is when you pass (s,t,u,m,p,e,d) as argument it merges the 4th,1st,3rd & the 2nd characters(tokens)

Now look at the third line of the program –

define begin decode(a,n,i,m,a,r,e)

Here the preprocessor replaces the macro “begin” with the expansion decode(a,n,i,m,a,r,e). According to the macro definition in the previous line the argument must be expanded so that the 4th,1st,3rd & the 2nd characters must be merged. In the argument(a,n,i,m,a,r,e) 4th,1st,3rd & the 2nd characters are ‘m’,’a’,’i’ & ‘n’.

so it will replace begin by main() by the preprocessor before the program is passed on for the compiler. That’s it…

Community
  • 1
  • 1
0

By using C++ constructors you write a C++ program without the main function with nothing it it. Let's say for example we can print a hello world without writing anything in the main function as follows:

class printMe{
   private:
   //
   public:
   printMe(){
       cout<<"Hello Wold! "<<endl;
  }
       protected:
       //
 }obj;

 int main(){}
crispengari
  • 7,901
  • 7
  • 45
  • 53
0

Maybe it's possible to compile a .data section and fill it with code?

Micromega
  • 12,486
  • 7
  • 35
  • 72
0

It depends what they mean.

Did they mean:

Write a program with no main() function.

Then generally speaking no.
But there are ways to cheat.

  • You can use the pre-processor to hide main() in plain sight.
  • Most compiler allow you to specify the entry point into your code.
    By default it is main(int,char*[])

Or did they mean:

Write a program that runs code without using main (to run your code).

This is a relatively simple trick. All objects in the global namespace run their constructors before main() is entered and destruction after main() exits. Thus all you need to do is define a class with a constructor that runs the code you want, then create an object in the global namespace.

Note: The compiler is allowed to optimize these objects for delayed load (but usually does not) but to be safe just put the global in the same file as the main function (that can be empty).

Martin York
  • 257,169
  • 86
  • 333
  • 562
0

Function main is only default label for address where program will start execution. So technically yes it`s possible, but you have to set name of function that will start execution in your environment.

-4

According to standards, main() is required and the starting point of hosted environments. That's why you've to use tricks to hide the obvious looking main, like the trick posted above.

#include <stdio.h>
#define decode(s,t,u,m,p,e,d) m##s##u##t
#define begin decode(a,n,i,m,a,t,e)

int begin()
{
    printf(" hello ");
}

Here, main is written by the macro tricks. It might not be clear at once, but it eventually leads to main. If this is the valid answer for your question, this could be done much easily, like this.

# include <stdio.h>
# define m main

int m()
{
    printf("Hell0");
}
Bharat Kul Ratan
  • 985
  • 2
  • 12
  • 24
  • could somebody tell me the reason for downvoting so that I could take care in future? – Bharat Kul Ratan Aug 14 '11 at 05:06
  • I did not downvote but the reason is clear enough, How is your answer different from [this](http://stackoverflow.com/questions/7050925/is-it-possible-to-write-a-program-without-using-main-function/7050982#7050982) answer & the comment I made on it? The time stamps tell me that was 5 hrs before you posted this answer. – Alok Save Aug 14 '11 at 05:10
  • @Als : thanks for making me understand the reason. By the way, that wasn't my answer. I was just trying to tell if this trick(I want to reference that one) is valid, then any much easier trick should work like my example. And I forgot to read the comments posted below the answers. – Bharat Kul Ratan Aug 14 '11 at 05:23
  • You will need to read the SO guidelines. In a nutshell post which answers the Q should be posted as Answers. comments, corrections, suggestions, criticism of answers should be posted as comments not answers. – Alok Save Aug 14 '11 at 05:27