Ist es möglich, ein Programm zu schreiben, ohne die Funktion main() zu verwenden?

Lesezeit: 8 Minuten

Benutzeravatar von Expert Novice
Experte Novize

Diese Frage bekomme ich immer wieder in Interviews gestellt:

Schreiben Sie ein Programm ohne Verwendung main() Funktion?

Einer meiner Freunde zeigte mir Code mit Makros, aber ich konnte ihn nicht verstehen.

Die Frage ist also:

Ist es wirklich möglich, ein Programm ohne zu schreiben und zu kompilieren? main()?

  • Scheint eine ziemlich dumme Interviewfrage zu sein… Vielleicht hast du ein Detail vergessen?

    – Gabriel Ščerbák

    13. August 2011 um 14:20 Uhr

  • Lieben Sie diese praktischen Interviewfragen nicht? /Sarkasmus

    – Peter Alexander

    13. August 2011 um 14:20 Uhr

  • Wie genau zeigt dies, ob der Kandidat Probleme lösen kann oder passt? Es ist schwer genug, lesbare Programme zu schreiben und zu warten, warum sollte man nach solchen Abscheulichkeiten fragen? Es sei denn, das Unternehmen heißt IOCCC.

    – Omri Barel

    13. August 2011 um 14:29 Uhr

  • Es kommt darauf an, was sie meinen. Meinten sie “ohne main()-Funktion”? oder meinten sie “Code ausführen, ohne ihn von main (auch indirekt) auszuführen”?

    – Martin York

    13. August 2011 um 16:10 Uhr


  • “Immer wieder gefragt werden”? Was, wurde gerade eine Liste mit dem Titel „TEH BESTEST C+ Interviewfragen“ im Internet veröffentlicht? Wo befinden Sie sich? Mit wem führen Sie ein Vorstellungsgespräch? Weil ich in die andere Richtung laufen möchte. Mein Vorschlag ist, dass Sie eliminieren, wenn Ihnen jemand diese Frage stellt Sie. Und übrigens, die Antwort lautet “Ja”, Sie können ein solches Programm “schreiben und kompilieren”, Sie können es nur nicht erfolgreich verknüpfen (zumindest auf einem standardmäßigen, gehosteten, kompatiblen System). Ich spalte vielleicht Haare, aber das wäre meine kluge Antwort, wenn mir die Frage gestellt würde.

    – Dan

    13. August 2011 um 20:58 Uhr

Benutzeravatar von Alok Save
Alok Speichern

Nein, das geht nicht, es sei denn, Sie schreiben ein Programm in a freestanding environment (Betriebssystemkern der eingebetteten Umgebung usw.), wo der Ausgangspunkt nicht sein muss main(). Nach dem C++-Standard main() ist der Ausgangspunkt jedes Programms in a hosted environment.

Gemäß:

C++03-Standard 3.6.1 Hauptfunktion

1 Ein Programm muss eine globale Funktion namens main enthalten, die den designierten Start des Programms darstellt. Es ist implementierungsabhängig, ob ein Programm in einer freistehenden Umgebung eine Hauptfunktion definieren muss. [ 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>

  • 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, 2011 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, 2011 at 14:55

  • @ Johannes Schaub – litb: Ah, I will add the exception of freestanding environments.

    – Alok Save

    Aug 13, 2011 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, 2011 at 15:03

Cheers and hth. - Alf's user avatar
Cheers and hth. – Alf

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.

  • 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 and Johannes Schaub’s answer. 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, 2011 at 22:20


  • @anonymous downvoter: please explain your reasons for downvoting, so that others may benefit from your insight(s).

    – Cheers and hth. – Alf

    Aug 14, 2011 at 2:46

  • 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, 2011 at 0:56


miku's user avatar
miku

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/

  • Actually, this 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, 2011 at 16:23


  • This code is not without main. gcc -E file.c would give you the code which is actually being compiled.

    – phoxis

    Aug 14, 2011 at 4:03

phoxis's user avatar
phoxis

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.

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.

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.

Mahesh's user avatar
Mahesh

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

 g++ -c noMain.cpp -o noMain.o

1396360cookie-checkIst es möglich, ein Programm zu schreiben, ohne die Funktion main() zu verwenden?

This website is using cookies to improve the user-friendliness. You agree by using the website further.

Privacy policy