It depends on your platform.
If you use GCC, you can have function declared with __attribute__((constructor))
. This function WILL be called before your main, even from dynamic library.
__attribute__((constructor))
void my_init()
{
/* do stuff; */
}
You can find more details in GCC documentation and in this SO question
There's some way how to do it in VC as well, even though not as simple. (See this SO question)
EDIT: If you link to some third party library, it may call some init function. Even if the library is in C. And there's no portable and generic way, how to detect it. And you probably don't want to mess with that as the library may depend it it being called before main starts.
If you really want to find out if it calls something, you'd have to look inside the binary.
In ELF files, there's a section .init_array
containing "pointers" to functions that will be invoked at start and it can be dumped using objdump (objdump -s -j .init_array <binary>
)
I assume there's similar section in PE files in windows, but I never worked with those, sorry.
EDIT2:
The main()
function starts your code. But there's stuff to do even before it's executed. When you compile your program, the compiler adds some code that is executed before the main()
and initializes environment for program (stack, C library...).
Under Linux this will be provided mainly by functions _start
and _init
. And as a feature, you can instruct it the compiler to call some your function(s) as well, inside the _init
function.
Dynamic library won't have the _start
function, but there's still _init
that will be called when the library's loaded. And a call to some user function can be included there as well.
In the case of static library it gets a bit more complicated, as the linker may remove some functions, when they're never called from you program. But once it's called (even indirectly from the library code) or just referenced somewhere in the library and never actually called, it will end up in you binary and will be called before main()
.
Some info about _start
and _init
can be found here.
Under windows the compiler and linker is different, but it should work in a similar way.