Two main functions - c++

Can we have two main() functions in a C++ program?

The standard explicitly says in 3.6.1:
A program shall contain a global function called main, which is the designated start of the program. [...] This function shall not be overloaded.
So there can one only be one one main function in the global scope in a program. Functions in other scopes that are also called main are not affected by this, there can be any number of them.

Only one function can be named main outside of any namespace, just as for any other name. If you have namespaces foo and bar (etc) you can perfectly well have functions named foo::main, bar::main, and so on, but they won't be treated as anything special from the system's point of view (only the function named main outside of any namespace is treated specially, as the program's entry point). Of course, from your main you could perfectly well call the various foo::main, bar::main, and so on.

Yes! Why not?
Consider the following code:
namespace ps
{
int main(){return 0;}
}
int main()
{
ps::main();
}
Its ::main() that will be called during execution.

You can't overload main() in the global scope.

A program can only have one entry point, but of course that one main() function can call out to other functions, based on whatever logic you care to specify. So if you are looking for a way to effectively compile two or more programs into a single executable, you can do something like this:
int main(int argc, char ** argv)
{
if (argc > 0) // paranoia
{
if (strstr(argv[0], "frogger")) return frogger_main(argc, argv);
else if (strstr(argv[0], "pacman")) return pacman_main(argc, argv);
else if (strstr(argv[0], "tempest")) return tempest_main(argc, argv);
}
printf("Hmm, I'm not sure what I should run.\n");
return 10;
}
... then just rename your 'other' main() functions to frogger_main(), pacman_main(), or whatever names you care to give them, and you'll have a program that runs as Frogger if the executable name has the word 'frogger' in it, or runs as PacMan if the executable has the name 'pacman' in it, etc.

In one single program, only one entry point is allowed.

Ooh, trick question!
Short answer: "It depends."
Long answer: As others have pointed out, you can have multiple functions named main so long as they are in different namespaces, and only the main in the root namespace (i.e. ::main) is used as the main program. In fact, some threading libraries' thread classes have a method named main that the library user overrides with the code they want run in the thread.
Now, assuming you're not doing any namespace tricks, if you try to define ::main in two different .cpp files, the files themselves will both compile, however, the linker will abort since there are two definitions named main; it can't tell which to link.
(A question I have for the gurus out there: in C++, do the function definitions int main() {} and extern "C" int main() {} generate functions with the same signature? I haven't tried it myself.)
And now for the time you can have more than one ::main in your program's source: if one main is in a library (.a or .so file), and another is in your source (.o) files, the one in your sources wins and the one in the library is dropped, and linking succeeds unless there's some other problem! If you didn't write a main, the library's main would win. This is actually done in the support libraries that ship with lex and yacc; they provide a barebones main so you don't have to write one for a quick parser.
Which leads to an interesting application: providing a main with every library. My libraries tend to be small and focused, and so I put a main.cpp in every one with a main that is test or utility code for the library. For example, my shared memory library has a main that allows all the functions for managing shared memory to be called from the command line. Then I can test a variety of cases with a bash script. Anything that links in the shared memory library gets the test code for free, or can dispose of it simply by defining their own main.
EDIT: Just to make sure folks are clear on the concept, I'm talking about a build that looks like:
gcc -c -o bar_main.o bar_main.cpp
ar -r libbar.a bar_main.o
ranlib libbar.a
gcc -c -o foo_main.o foo_main.cpp
gcc -o foo foo_main.o -L. -lbar
In this example, the main in foo_main.o beats the main in bar_main.o. The standard doesn't define this behavior because they don't care. There's a lot of nonstandard things that people use anyway; Linux is an example with its use of C bitfields. ld has worked this way longer than I've known how to type.
Seriously, guys, feel free to strictly adhere to standards if you need to turn out least-common-denominator code. But if you have the luxury of working on a platform that can build lex and yacc programs, by all means, consider taking advantage of it.

there is only one entry point in the global scope.

Related

how to start the execution of a program in c/c++ from a different function,but not main() [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Does the program execution always start from main in C?
i want to start the execution of my program which contains 2 functions (excluding main)
void check(void)
void execute(void)
i want to start my execution from check(), is it possible in c/c++?
You can do this with a simple wrapper:
int main()
{
check();
}
You can't portably do it in any other way since the standard explicitly specifies main as the program entry point.
EDIT for comment: Don't ever do this. In C++ you could abuse static initialization to have check called before main during static init, but you still can't call main legally from check. You can just have check run first. As noted in a comment this doesn't work in C because it requires constant initializers.
// At file scope.
bool abuse_the_language = (check(), true);
int main()
{
// No op if desired.
}
Various linkers have various options to specify the entry point. Eg. Microsoft linker uses /ENTRY:function:
The /ENTRY option specifies an entry point function as the starting
address for an .exe file or DLL.
GNU's ld uses the -e or ENTRY() in the command file.
Needles to say, modifying the entry point is a very advanced feature which you must absolutely understand how it works. For one, it may cause skipping the loading the standard libraries initialization.
int main()
{
check();
return 0;
}
Calling check from main seems like the most logical solution, but you could still explore using /ENTRY to define another entry point for your application. See here for more info.
You cannot start in something other than main, although there are ways to have some code execute before main.
Putting code in a static initialization block will have the code run prior to main; however, it won't be 100% controllable. while you can be assured it runs prior to main, you cannot specify the order that two static initialization blocks will run prior to them both executing before main.
Linkers and loaders both have the concept of main held as a shared "understood" start of a C / C++ program; however, there is code that runs prior to main. This code is responsible for "setting up the environment" of the program (things like setting up stdin or cin). By putting code in a static initialization block, you effectively say, "hey you need to do this too to have the right environment". Generally, this should be something small, that can stand independently in execution order of other items.
If you need two or three things to execute in order before main, then make them into proper functions and call them at the beginning of main.
There is a contrived way to achieve that, but it is nothing more than a hack.
The idea is to create a static library containing the main function, and make it call your "check" function.
The linker will resolve the symbol when linking against your "program", and your "program" code will indeed not have a main by itself.
This is NOT recommended, unless you have very specific needs (an example that pops to mind is Windows Screensavers, as the helper library that comes with the Windows SDK has a main function that performs specific initialization like parsing the command line).
It may be supportted by the compiler. For example, gcc, you can use -nostartfiles and --entry=xxx to set the entry point of the program. The default entry point is _start, which will call the function main.
You can "intercept" the call to main by creating an object before the main starts. The constructor needs to execute your function.
#include <iostream>
void foo()
{
// do stuff
std::cout<<"exiting from foo" <<std::endl;
}
struct A
{
A(){ foo(); };
};
static A a;
int main()
{
// something
std::cout<<"starting main()" <<std::endl;
}
I have found solution to my own question.
we can simply use
#pragma startup function-name <priority>
#pragma exit function-name <priority>
These two pragmas allow the program to specify function(s) that should be called either upon program startup (before the main function is called), or program exit (just before the program terminates through _exit).
The specified function-name must be a previously declared function taking no arguments and returning void; in other words, it should be declared as:
void func(void);
The optional priority parameter should be an integer in the range 64 to 255. The highest priority is 0. Functions with higher priorities are called first at startup and last at exit. If you don't specify a priority, it defaults to 100.
thanks!

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()?
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>
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.
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/
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.
Yes it possible to compile with out main but you cannot pass the linking phase though.
g++ -c noMain.cpp -o noMain.o
"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).
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.
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 ");
}
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.
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().
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...
}
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 :-)
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
Maybe it's possible to compile a .data section and fill it with code?
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).
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.
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;
}
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…
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(){}
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");
}

Do you really need a main() in C++?

From what I can tell you can kick off all the action in a constructor when you create a global object. So do you really need a main() function in C++ or is it just legacy?
I can understand that it could be considered bad practice to do so. I'm just asking out of curiosity.
If you want to run your program on a hosted C++ implementation, you need a main function. That's just how things are defined. You can leave it empty if you want of course. On the technical side of things, the linker wants to resolve the main symbol that's used in the runtime library (which has no clue of your special intentions to omit it - it just still emits a call to it). If the Standard specified that main is optional, then of course implementations could come up with solutions, but that would need to happen in a parallel universe.
If you go with the "Execution starts in the constructor of my global object", beware that you set yourself up to many problems related to the order of constructions of namespace scope objects defined in different translation units (So what is the entry point? The answer is: You will have multiple entry points, and what entry point is executed first is unspecified!). In C++03 you aren't even guaranteed that cout is properly constructed (in C++0x you have a guarantee that it is, before any code tries to use it, as long as there is a preceeding include of <iostream>).
You don't have those problems and don't need to work around them (wich can be very tricky) if you properly start executing things in ::main.
As mentioned in the comments, there are however several systems that hide main from the user by having him tell the name of a class which is instantiated within main. This works similar to the following example
class MyApp {
public:
MyApp(std::vector<std::string> const& argv);
int run() {
/* code comes here */
return 0;
};
};
IMPLEMENT_APP(MyApp);
To the user of this system, it's completely hidden that there is a main function, but that macro would actually define such a main function as follows
#define IMPLEMENT_APP(AppClass) \
int main(int argc, char **argv) { \
AppClass m(std::vector<std::string>(argv, argv + argc)); \
return m.run(); \
}
This doesn't have the problem of unspecified order of construction mentioned above. The benefit of them is that they work with different forms of higher level entry points. For example, Windows GUI programs start up in a WinMain function - IMPLEMENT_APP could then define such a function instead on that platform.
Yes! You can do away with main.
Disclaimer: You asked if it were possible, not if it should be done. This is a totally un-supported, bad idea. I've done this myself, for reasons that I won't get into, but I am not recommending it. My purpose wasn't getting rid of main, but it can do that as well.
The basic steps are as follows:
Find crt0.c in your compiler's CRT source directory.
Add crt0.c to your project (a copy, not the original).
Find and remove the call to main from crt0.c.
Getting it to compile and link can be difficult; How difficult depends on which compiler and which compiler version.
Added
I just did it with Visual Studio 2008, so here are the exact steps you have to take to get it to work with that compiler.
Create a new C++ Win32 Console Application (click next and check Empty Project).
Add new item.. C++ File, but name it crt0.c (not .cpp).
Copy contents of C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\crt\src\crt0.c and paste into crt0.c.
Find mainret = _tmain(__argc, _targv, _tenviron); and comment it out.
Right-click on crt0.c and select Properties.
Set C/C++ -> General -> Additional Include Directories = "C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\crt\src".
Set C/C++ -> Preprocessor -> Preprocessor Definitions = _CRTBLD.
Click OK.
Right-click on the project name and select Properties.
Set C/C++ -> Code Generation -> Runtime Library = Multi-threaded Debug (/MTd) (*).
Click OK.
Add new item.. C++ File, name it whatever (app.cpp for this example).
Paste the code below into app.cpp and run it.
(*) You can't use the runtime DLL, you have to statically link to the runtime library.
#include <iostream>
class App
{
public: App()
{
std::cout << "Hello, World! I have no main!" << std::endl;
}
};
static App theApp;
Added
I removed the superflous exit call and the blurb about lifetime as I think we're all capable of understanding the consequences of removing main.
Ultra Necro
I just came across this answer and read both it and John Dibling's objections below. It was apparent that I didn't explain what the above procedure does and why that does indeed remove main from the program entirely.
John asserts that "there is always a main" in the CRT. Those words are not strictly correct, but the spirit of the statement is. Main is not a function provided by the CRT, you must add it yourself. The call to that function is in the CRT provided entry point function.
The entry point of every C/C++ program is a function in a module named 'crt0'. I'm not sure if this is a convention or part of the language specification, but every C/C++ compiler I've come across (which is a lot) uses it. This function basically does three things:
Initialize the CRT
Call main
Tear down
In the example above, the call is _tmain but that is some macro magic to allow for the various forms that 'main' can have, some of which are VS specific in this case.
What the above procedure does is it removes the module 'crt0' from the CRT and replaces it with a new one. This is why you can't use the Runtime DLL, there is already a function in that DLL with the same entry point name as the one we are adding (2). When you statically link, the CRT is a collection of .lib files, and the linker allows you to override .lib modules entirely. In this case a module with only one function.
Our new program contains the stock CRT, minus its CRT0 module, but with a CRT0 module of our own creation. In there we remove the call to main. So there is no main anywhere!
(2) You might think you could use the runtime DLL by renaming the entry point function in your crt0.c file, and changing the entry point in the linker settings. However, the compiler is unaware of the entry point change and the DLL contains an external reference to a 'main' function which you're not providing, so it would not compile.
Generally speaking, an application needs an entry point, and main is that entry point. The fact that initialization of globals might happen before main is pretty much irrelevant. If you're writing a console or GUI app you have to have a main for it to link, and it's only good practice to have that routine be responsible for the main execution of the app rather than use other features for bizarre unintended purposes.
Well, from the perspective of the C++ standard, yes, it's still required. But I suspect your question is of a different nature than that.
I think doing it the way you're thinking about would cause too many problems though.
For example, in many environments the return value from main is given as the status result from running the program as a whole. And that would be really hard to replicate from a constructor. Some bit of code could still call exit of course, but that seems like using a goto and would skip destruction of anything on the stack. You could try to fix things up by having a special exception you threw instead in order to generate an exit code other than 0.
But then you still run into the problem of the order of execution of global constructors not being defined. That means that in any particular constructor for a global object you won't be able to make any assumptions about whether or not any other global object yet exists.
You could try to solve the constructor order problem by just saying each constructor gets its own thread, and if you want to access any other global objects you have to wait on a condition variable until they say they're constructed. That's just asking for deadlocks though, and those deadlocks would be really hard to debug. You'd also have the issue of which thread exiting with the special 'return value from the program' exception would constitute the real return value of the program as a whole.
I think those two issues are killers if you want to get rid of main.
And I can't think of a language that doesn't have some basic equivalent to main. In Java, for example, there is an externally supplied class name who's main static function is called. In Python, there's the __main__ module. In perl there's the script you specify on the command line.
If you have more than one global object being constructed, there is no guarantee as to which constructor will run first.
If you are building static or dynamic library code then you don't need to define main yourself, but you will still wind up running in some program that has it.
If you are coding for windows, do not do this.
Running your app entirely from within the constructor of a global object may work just fine for quite awhile, but sooner or later you will make a call to the wrong function and end up with a program that terminates without warning.
Global object constructors run during the startup of the C runtime.
The C runtime startup code runs during the DLLMain of the C runtime DLL
During DLLMain, you are holding the DLL loader lock.
Tring to load another DLL while already holding the DLL loader lock results in a swift death for your process.
Compiling your entire app into a single executable won't save you - many Win32 calls have the potential to quietly load system DLLs.
There are implementations where global objects are not possible, or where non-trivial constructors are not possible for such objects (especially in the mobile and embedded realms).

in c++ main function is the entry point to program how i can change it to an other function?

I was asked an interview question to change the entry point of a C or C++ program from main() to any other function. How is it possible?
In standard C (and, I believe, C++ as well), you can't, at least not for a hosted environment (but see below). The standard specifies that the starting point for the C code is main. The standard (c99) doesn't leave much scope for argument:
5.1.2.2.1 Program startup: (1) The function called at program startup is named main.
That's it. It then waffles on a bit about parameters and return values but there's really no leeway there for changing the name.
That's for a hosted environment. The standard also allows for a freestanding environment (i.e., no OS, for things like embedded systems). For a freestanding environment:
In a freestanding environment (in which C program execution may take place without any benefit of an operating system), the name and type of the function called at program startup are implementation-defined. Any library facilities available to a freestanding program, other than the minimal set required by clause 4, are implementation-defined.
You can use "trickery" in C implementations so that you can make it look like main isn't the entry point. This is in fact what early Windows compliers did to mark WinMain as the start point.
First way: a linker may include some pre-main startup code in a file like start.o and it is this piece of code which runs to set up the C environment then call main. There's nothing to stop you replacing that with something that calls bob instead.
Second way: some linkers provide that very option with a command-line switch so that you can change it without recompiling the startup code.
Third way: you can link with this piece of code:
int main (int c, char *v[]) { return bob (c, v); }
and then your entry point for your code is seemingly bob rather than main.
However, all this, while of possibly academic interest, doesn't change the fact that I can't think of one single solitary situation in my many decades of cutting code, where this would be either necessary or desirable.
I would be asking the interviewer: why would you want to do this?
The entry point is actually the _start function (implemented in crt1.o) .
The _start function prepares the command line arguments and then calls main(int argc,char* argv[], char* env[]),
you can change the entry point from _start to mystart by setting a linker parameter:
g++ file.o -Wl,-emystart -o runme
Of course, this is a replacement for the entry point _start so you won't get the command line arguments:
void mystart(){
}
Note that global/static variables that have constructors or destructors must be initialized at the beginning of the application and destroyed at the end. Keep that in mind if you are planning on bypassing the default entry point which does it automatically.
From C++ standard docs 3.6.1 Main Function,
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.
So, it does depend on your compiler/linker...
If you are on VS2010, this could give you some idea
As it is easy to understand, this is not mandated by the C++ standard and falls in the domain of 'implemenation specific behavior'.
This is highly speculative, but you might have a static initializer instead of main:
#include <iostream>
int mymain()
{
std::cout << "mymain";
exit(0);
}
static int sRetVal = mymain();
int main()
{
std::cout << "never get here";
}
You might even make it 'Java-like', by putting the stuff in a constructor:
#include <iostream>
class MyApplication
{
public:
MyApplication()
{
std::cout << "mymain";
exit(0);
}
};
static MyApplication sMyApplication;
int main()
{
std::cout << "never get here";
}
Now. The interviewer might have thought about these, but I'd personally never use them. The reasons are:
It's non-conventional. People won't understand it, it's nontrivial to find the entry point.
Static initialization order is nondeterministic. Put in another static variable and you'll never now if it gets initialized.
That said, I've seen it being used in production instead of init() for library initializers. The caveat is, on windows, (from experience) your statics in a DLL might or might not get initialized based on usage.
Modify the crt object that actually calls the main() function, or provide your own (don't forget to disable linking of the normal one).
With gcc, declare the function with attribute((constructor)) and gcc will execute this function before any other code including main.
For Solaris Based Systems I have found this. You can use the .init section for every platforms I guess:
pragma init (function [, function]...)
Source:
This pragma causes each listed function to be called during initialization (before main) or during shared module loading, by adding a call to the .init section.
It's very simple:
As you should know when you use constants in c, the compiler execute a kind of 'macro' changing the name of the constant for the respective value.
just include a #define argument in the beginning of your code with the name of start-up function followed by the name main:
Example:
#define my_start-up_function (main)
I think it is easy to remove the undesired main() symbol from the object before linking.
Unfortunately the entry point option for g++ is not working for me(the binary crashes before entering the entry point). So I strip undesired entry-point from object file.
Suppose we have two sources that contain entry point function.
target.c contains the main() we do not want.
our_code.c contains the testmain() we want to be the entry point.
After compiling(g++ -c option) we can get the following object files.
target.o, that contains the main() we do not want.
our_code.o that contains the testmain() we want to be the entry point.
So we can use the objcopy to strip undesired main() function.
objcopy --strip-symbol=main target.o
We can redefine testmain() to main() using objcopy too.
objcopy --redefine-sym testmain=main our_code.o
And then we can link both of them into binary.
g++ target.o our_code.o -o our_binary.bin
This works for me. Now when we run our_binary.bin the entry point is our_code.o:main() symbol which refers to our_code.c::testmain() function.
On windows there is another (rather unorthodox) way to change the entry point of a program: TLS. See this for more explanations: http://isc.sans.edu/diary.html?storyid=6655
Yes,
We can change the main function name to any other name for eg. Start, bob, rem etc.
How does the compiler knows that it has to search for the main() in the entire code ?
Nothing is automatic in programming.
somebody has done some work to make it looks automatic for us.
so it has been defined in the start up file that the compiler should search for main().
we can change the name main to anything else eg. Bob and then the compiler will be searching for Bob() only.
Changing a value in Linker Settings will override the entry point. i.e., MFC applications use a value of 'Windows (/SUBSYSTEM:WINDOWS)' to change entry point from main() to CWinApp::WinMain().
Right clicking on solution > Properties > Linker > System > Subsystem > Windows (/SUBSYSTEM:WINDOWS)
...
Very practical benefit to modifying entry point:
MFC is a framework we take advantage of to write Windows applications in C++. I know it's ancient, but my company maintains one for legacy reasons! You will not find a main() in MFC code. MSDN says the entry point is WinMain(), instead. Thus, you can override the WinMain() of your base CWinApp object. Or, most people override CWinApp::InitInstance() because the base WinMain() will call it.
Disclaimer: I use empty parentheses to denote a method, without caring how many arguments.

Two 'main' functions in C/C++

Can I write a program in C or in C++ with two main functions?
No. All programs have a single main(), that's how the compiler and linker generate an executable that start somewhere sensible.
You basically have two options:
Have the main() interpret some command line arguments to decide what actual main to call. The drawback is that you are going to have an executable with both programs.
Create a library out of the shared code and compile each main file against that library. You'll end up with two executables.
You can have two functions called main. The name is not special in any way and it's not reserved. What's special is the function, and it happens to have that name. The function is global. So if you write a main function in some other namespace, you will have a second main function.
namespace kuppusamy {
int main() { return 0; }
}
int main() { kuppusamy::main(); }
The first main function is not special - notice how you have to return explicitly.
Yes; however, it's platform specific instead of standard C, and if you ask about what you really want to achieve (instead of this attempted solution to that problem), then you'll likely receive answers which are more helpful for you.
No, a program can have just 1 entry point(which is main()). In fact, more generally, you can only have one function of a given name in C.
If one is static and resides in a different source file I don't see any problem.
No, main() defines the entry point to your program and you must only one main() function(entry point) in your program.
Frankly speaking your question doesn't make much sense to me.
What do you mean by "main function"? If you mean the first function to execute when the program starts, then you can have only one. (You can only have one first!)
If you want to have your application do different things on start up, you can write a main function which reads the command line (for example) and then decides which other function to call.
In some very special architecture, you can. This is the case of the Cell Processor where you have a main program for the main processor (64-bit PowerPC Processors Element called PPE) and one or many main program for the 8 different co-processor (32-bit Synergistic Processing Element called SPE).
No, you cannot have more than one main() function in C language. In standard C language, the main() function is a special function that is defined as the entry point of the program. There cannot be more than one copy of ANY function you create in C language, or in any other language for that matter - unless you specify different signatures. But in case of main(), i think you got no choice ;)
No,The main() is the entry point to your program,since u can't have two entry points you cant have two main().
You can write it, and it'll compile, but it won't link (unless your linker is non-comformant)
The idiom is to dispatch on the value of argv[0]. With hardlinks (POSIX) you don't even lose diskspace.
Standard C doesn’t allow nested functions but GCC allows them.
void main()
{
void main()
{
printf(“stackoverflow”);
}
printf(“hii”);
}
The o/p for this code will be -hii
if you use GCC compiler.
There is a simple trick if you want to use 2 main() in your program such that both are successfully executed;you can use define.Example-
void main()
{
printf("In 1st main\n");
func1();
}
#define main func1
void main()
{
printf("In 2nd main\n");
}
Here the o/p will be:
In 1st main
In 2nd main
NOTE:here warning conflicting types of func1 will be generated.
And yes don’t change the place of define.