1

I have a project that have many files contain main function, and I want to add some initialization code at the beginning of each main function without change anything directly on source files. Maybe through some kind of wrapper function? I'm not sure how to implement this. Thanks for any help.

AetX
  • 193
  • 6

2 Answers2

3

If you are compiling with gcc, you can look at this link maybe?

An example would be:

void runBeforeMain(void) __attribute__ ((constructor)); 

declaration in a header file that you include, etc...

The function definition can come after.

As a second option, you can look at makefiles.

Community
  • 1
  • 1
Mini
  • 445
  • 5
  • 17
  • Thanks! The first solution works! But I'm wondering how about using makefile? Could you illustrate with an example? – AetX Mar 08 '19 at 19:15
0

If you are not using the word main for any other variable, etc, then you can probably do

#define main(...) main(int argc, char** argv){\
/****    initialization stuff.   ****/\
/*get rid of the "{" in your original line*/ //

You can put it into your common header file and if this file exists you have probably included it in every other source files already. If not, you may add a -include xxx.h flag to your build script (not sure if this is very portable, at least it works for gcc and clang).

BlueFlo0d
  • 180
  • 9