1

Can a program be written without main() function?

I have written this code and saved a filename as withoutmain.c and getting an error as

undefined reference to 'WinMain@16'"

My code

 #include<stdio.h>
    #include<windows.h>
    extern void _exit(register int code);
    _start(){
      int retval;
      retval=myFunc();
      _exit(retval);
    }
    int myFunc(void){
     printf("Hiii Pratishtha");
     return 0;
    }

Please provide me the solution of this problem and also the proper memory construction of code and what is happening at the compiler end of this program. Thank you!

Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94
  • The solution is simple: do not write a program without `main()`. – Rudy Velthuis Jul 29 '16 at 08:07
  • There must be a way to specify the entry point in your linker options, but for gcc I don't know it. Why don't you look it up in the documentation? – Medinoc Jul 29 '16 at 08:39
  • Possible duplicate of [How to change entry point of C program with gcc ?](http://stackoverflow.com/questions/7494244/how-to-change-entry-point-of-c-program-with-gcc) – Medinoc Jul 29 '16 at 08:41
  • If your question is Windows-specific, at least tag it as such (and in fact, specify your compilation environment - which compiler etc). The answer is markedly different if you are asking a general C question. – davmac Jul 29 '16 at 10:08

1 Answers1

1

Can a program be written without main() function?

Yes there can be a C program without a main function. I would suggest two solutions.......

1) Using a macro that defines main

#include<stdio.h>
#include<windows.h>
#define _start main
extern void _exit(register int code);

int myFunc(void){
    printf("Hiii Pratishtha");
    return 0;
}

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

2) Using Entry Point (Assuming you are using visual studio)

To set this linker option in the Visual Studio development environment

/ENTRY:function

A function that specifies a user-defined starting address for an .exe file or DLL.

  1. Open the project's Property Pages dialog box. For details, see Setting Visual C++ Project Properties.
  2. LClick the Linker folder.
  3. Click the Advanced property page.
  4. Modify the Entry Point property.

OR

if you are using gcc then

-Wl,-e_start

the -Wl,... thing passes arguments to the linker, and the linker takes a -e argument to set the entry function

Mohan
  • 1,871
  • 21
  • 34