Two 'main' functions in C/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.

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");
}

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

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.

Is there any way a C/C++ program can crash before main()?

Is there any way a program can crash before main()?
With gcc, you can tag a function with the constructor attribute (which causes the function to be run before main). In the following function, premain will be called before main:
#include <stdio.h>
void premain() __attribute__ ((constructor));
void premain()
{
fputs("premain\n", stdout);
}
int main()
{
fputs("main\n", stdout);
return 0;
}
So, if there is a crashing bug in premain you will crash before main.
Yes, at least under Windows. If the program utilizes DLLs they can be loaded before main() starts. The DllMain functions of those DLLs will be executed before main(). If they encounter an error they could cause the entire process to halt or crash.
The simple answer is: Yes.
More specifically, we can differentiate between two causes for this. I'll call them implementation-dependent and implementation-independent.
The one case that doesn't depend on your environment at all is that of static objects in C++, which was mentioned here. The following code dies before main():
#include <iostream>
class Useless {
public:
Useless() { throw "You can't construct me!"; }
};
static Useless object;
int main() {
std::cout << "This will never be printed" << std::endl;
return 0;
}
More interesting are the platform-dependent causes. Some were mentioned here. One that was mentioned here a couple of times was the usage of dynamically linked libraries (DLLs in windows, SOs in Linux, etc.) - if your OS's loader loads them before main(), they might cause your application do die before main().
A more general version of this cause is talking about all the things your binary's entry point does before calling your entry point(main()). Usually when you build your binary there's a pretty serious block of code that's called when your operating system's loader starts to run your binary, and when it's done it calls your main(). One common thing this code does is initializing the C/C++ standard library. This code can fail for any number of reasons (shortage of any kind of system resource it tries to allocate for one).
One interesting way on for a binary to execute code before main() on windows is using TLS callbacks (google will tell you more about them). This technique is usually found in malware as a basic anti-debugging trick (this trick used to fool ollydbg back then, don't know if it still does).
The point is that your question is actually equivalent to "is there a way that loading a binary would cause user code to execute before the code in main()?", and the answer is hell, yeah!
If you have a C++ program it can initialize variables and objects through functions and constructors before main is entered. A bug in any of these could cause a program to crash.
certainly in c++; static objects with contructors will get called before main - they can die
not sure about c
here is sample
class X
{
public:
X()
{
char *x = 0;
*x = 1;
}
};
X x;
int main()
{
return 0;
}
this will crash before main
Any program that relies on shared objects (DLLs) being loaded before main can fail before main.
Under Linux code in the dynamic linker library (ld-*.so) is run to supply any library dependancies well before main. If any needed libraries are not able to be located, have permissions which don't allow you to access them, aren't normal files, or don't have some symbol that the dynamic linker that linked your program thought that it should have when it linked your program then this can cause failure.
In addition, each library gets to run some code when it is linked. This is mostly because the library may need to link more libraries or may need to run some constructors (even in a C program, the libraries could have some C++ or something else that uses constroctors).
In addition, standard C programs have already created the stdio FILEs stdin, stdout, and stderr. On many systems these can also be closed. This implies that they are also free()ed, which implies that they (and their buffers) were malloc()ed, which can fail. It also suggests that they may have done some other stuff to the file descriptors that those FILE structures represent, which could fail.
Other things that could possibly happen could be if the OS were to mess up setting up the enviromental variables and/or command line arguments that were passed to the program. Code before main is likely to have had to something with this data before calling main.
Lots of things happen before main. Any of them can concievably fail in a fatal way.
I'm not sure, but if you have a global variable like this :
static SomeClass object;
int main(){
return 0;
}
The 'SomeClass' constructor could possibly crash the program before the main being executed.
There are many possibilities.
First, we need to understand what actually goes on before main is executed:
Load of dynamic libraries
Initialization of globals
One some compilers, some functions can be executed explicitly
Now, any of this can cause a crash in several ways:
the usual undefined behavior (dereferencing null pointer, accessing memory you should not...)
an exception thrown > since there is no catch, terminate is called and the program end
It's really annoying of course and possibly hard to debug, and that is why you should refrain from executing code before main as much as possible, and prefer lazy initialization if you can, or explicit initialization within main.
Of course, when it's a DLL failing and you can't modify it, you're in for a world of pain.
Sort of:
http://blog.ksplice.com/2010/03/libc-free-world/
If you compile without standard library, like this:
gcc -nostdlib -o hello hello.c
it won't know how to run main() and will crash.
Global and static objects in a C++ program will have their constructors called before the first statement in main() is executed, so a bug in one of the constructors can cause a crash.
This can't happen in C programs, though.
It depends what you mean by "before main", but if you mean "before any of your code in main is actually executed" then I can think of one example: if you declare a large array as a local variable in main, and the size of this array exceeds the available stack space, then you may well get a stack overflow on entry to main, before the first line of code executes.
A somewhat contrived example would be:
int a = 1;
int b = 0;
int c = a / b;
int main()
{
return 0;
}
It's unlikely that you'd ever do something like this, but if you're doing a lot of macro-magic, it is entirely possible.
class Crash
{
public:
Crash( int* p )
{ *p = 0; }
};
static Crash static_crash( 0 );
void main()
{
}
I had faced the same issue. The root-cause found was.. Too many local variables(huge arrays) were initialized in the main process leading the local variables size exceeding 1.5 mb.
This results in a big jump as the stack pointer is quite large and the OS detects this jump as invalid and crashes the program as it could be malicious.
To debug this.
1. Fire up GDB
2. Add a breakpoint at main
3. disassemble main
4. Check for sub $0xGGGGGGG,%esp
If this GGGGGG value is too high then you will see the same issue as me.
So check the total size of all the local variables in the main.
Sure, if there's a bug in the operating system or the runtime code. C++ is particularly notorious for this behaviour, but it can still happen in C.
You haven't said which platform/libc. In the embedded world there are frequently many things which run before main() - largely to do with platform setup - which can go wrong. (Or indeed if you are using a funky linker script on a regular OS, all bets are off, but I guess that's pretty rare.)
some platform abstraction libraries override (i personally only know of C++ libraries like Qt or ACE, which do this, but maybe some C libraries do something like that aswell) "main", so that they specify a platform-specific main like a int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ); and setup some library stuff, convert the command line args to the normal int argc, char* argv[] and then call the normal int main(int argc, char* argv[])
Of course such libraries could lead to a crash when they did not implement this correctly (maybe cause of malformed command line args).
And for people who dont know about this, this may look like a crash before main
Best suited example to crash a program before main for stackoverflow:
int main() {
char volatile stackoverflow[1000000000] = {0};
return 0;
}