C defining macro which would be processed only once and not recursively

StackOverflow https://stackoverflow.com/questions/23516406

  •  17-07-2023
  •  | 
  •  

سؤال

I want to change main so that it calls one function before doing anything else. So I written code like this

#include <stdio.h>

void test()
{
    printf("\nTEST\n");
#undef main
    main(1,NULL);
}

int main(int argc, char** argv)
{
    printf("\nHello World\n");
}

and compiled it like

cc -g -Dmain=test test.c -o test

but still it prints "Hello World" and not "TEST". What should I do so that I can call test just before main does anything else?

Thanks

هل كانت مفيدة؟

المحلول

If you want call other function, before main, gcc provides __attribute__

for example:

int test(void) __attribute__ ((constructor));

int test()
{
    printf("\nTEST\n");
    return 0;
}

int main(int argc, char** argv)
{
    printf("\nHello World\n");
    return 0;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top