Is there a way to find out the address of main() in C or C++ ? Since it is itself a function ,would there be an address of it own ?
If for any system you can't find the address of main.. put an invocation to a function foo() as the only statement in main, have main return whatever it returns and use the address of foo rather than main.
Note that calling main won't necessarily restart your code, even if there are no static/global variables. The compiler generates start up code before actually calling main.
If you want to breakpoint before this call to main write something like:
static int i=foo();
and foo will be called during the earlier data initialisation step.
Sure. Simply go ahead and do it.
#include <stdio.h>
int main(void)
{
printf("%p\n", &main);
}
It is not permitted to take main
's address so, for your purposes, there isn't one:
[C++11: 3.6.1/3]:
The function main shall not be used within a program. [..]
However, in GCC you can take the same approach as you would in C, via a compiler extension:
#include <iostream>
int main()
{
std::cout << (void*)&main << '\n';
}
You will receive a warning that this is not compliant.
I wasn't 100% sure whether the question was meant from within a program using C/++ or to retrieve address of the main()
function created with C/C++ (meaning from the command line).
Since it looks like you've received several good answers on how to get the address from within the program, I thought I'd mention you can get this info from nm
as well.
nm program|grep main