0

I want get the address of exit library function and then assign this address to a global variable.

  //test3.c

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 
  4   int fp = &exit;
  5 
  6 int main(){
  7   printf("fp=%d\n",fp);
  8   return 0;
  9 }

But one error comes out when I compile the above test3.c program using gcc.

$ gcc -o test3 test3.c
test3.c:4:12: warning: initialization makes integer from pointer without a cast [enabled by default]
test3.c:4:3: error: initializer element is not computable at load time

When I get and assign the address of exit to a local variable in main function, there is no error.

  //test4.c

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 
  4 int main(){
  5   int fp = &exit;
  6   printf("fp=%d\n",fp);
  7   return 0;
  8 }

I can print the result:

$ gcc -o test4 test4.c
test4.c: In function ‘main’:
test4.c:5:12: warning: initialization makes integer from pointer without a cast [enabled by default]
$ ./test4
fp=4195408

How can I assign the address of exit to a global variable?

breeze
  • 51
  • 3
  • See also http://stackoverflow.com/questions/9410/how-do-you-pass-a-function-as-a-parameter-in-c/9413#9413 – hivert Jul 24 '13 at 11:47

1 Answers1

3

You should declare fp with the correct type (ie pointer to a function taking an int and returning nothing):

void (*fp)(int) = &exit;

Not sure what you are trying to do with the printf then. If you want to print the address use %p instead of %d.

hivert
  • 10,579
  • 3
  • 31
  • 56
  • Thank you. But if I assign the address of exit to the local variable in main function, there is no error. – breeze Jul 24 '13 at 11:52
  • Yes but there is a big warning which should raise your attention: ``initialization makes integer from pointer without a cast`` – hivert Jul 24 '13 at 11:54
  • I think the warning is not the most important problem. I can use gcc option to suppress this warning. – breeze Jul 24 '13 at 11:58
  • 1
    Sure you can suppress the warning, but that would be a bad idea. The warning is not a **problem** but a **solution hint**. It tells you exactly what was wrong: assigning a pointer to an ``int``. So the solution was fix the type of the ``int`` variable. – hivert Jul 24 '13 at 12:04
  • I have tried to use void(*fp)(int) = &exit. It has been compiled successfully. But why do using function pointer in the global scope right? The address of exit seemly can only be get after linking. – breeze Jul 24 '13 at 12:49
  • @breeze getting rid of warnings is right if you are trying to figure out what it is for but its worse if you are trying to suppress it just to make your program work ..... also exit is a function so hivert's explanation is according to it . – 0decimal0 Jul 24 '13 at 13:17