2

I want to execute user define function before main(). Is it possible to execute a function before main() in c?

sum(int a, int b) {   return (a+b); }

g_sum = sum(1, 5);

main(){
  sum(5, 6);
  printf("%d", g_sum);
}
sutirtha
  • 375
  • 3
  • 21
  • 1
    In `C++` this would be quite okay. What compiler do you use? With `GCC` you can do something with `__attribute__((constructor))` – starrify Feb 21 '14 at 05:21
  • Your code won't compile ... you can't have statements or expressions at file level. – Jim Balter Feb 21 '14 at 05:33

1 Answers1

6

Is it possible to execute a function before main()

Yes it is possible if you are using gcc and g++ compilers then it can be done by using __attribute__((constructor))

Example:

#include <stdio.h>

void beforeMain (void) __attribute__((constructor));

void beforeMain (void)
{
  printf ("\nThis is before main\n");
}

int main ()
{
 printf ("\nThis is my main \n");
 return 0;
}
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • 1
    Just curiosity, In what scenario we need this functionality? – Meluha Feb 21 '14 at 06:06
  • @SagarKotecha:- I am not very sure of the exact scenario right now but it is like C runtime works by providing an entry point for the operating system to execute when you execute the binary. That entry point runs code specific to the compiler implementation. The initialization code will be set accordingly, and then main() function is called(with any command line parameters if provided). Any other code outside of the C runtime proper that is executed before main() is called is a mechanism outside of the C language (or an extension to the C language provided by the compiler). – Rahul Tripathi Feb 21 '14 at 06:22