I have function pointer, that is declared as follows in file 1.h
// file : 1.h
typedef void (*my_func_ptr_T)(int , int);
In file 1.c I create a global instance and initialize it
// file 1.c
my_func_ptr_T func;
void callback (my_func_ptr_T _ptr) {
func = _ptr;
}
Now, how can i use this function ptr 'func' in another file say 2.c
// file 2.c
void do_callback() {
// i want to do this
func(1,2);
}
Check the below changes
// file : 1.h
typedef void (*my_func_ptr_T)(int , int);
extern my_func_ptr_T func;
//file 1.c
#include "1.h"
//func is visible
// file 2.c
#include "1.h"
//func is visible
Changing 2.c
to below will help. Leave 1.h
and 1.c
unchanged.
#include "1.h"
extern my_func_ptr_T func;
void do_callback() {
func(1,2);
}
//sample sum function
void sum( int a, int b ) {
printf ("SUM : %d\n", a+b);
}
//main
int main() {
func = sum;
do_callback( );
}
It is important to understand that, keyword extern
doesn't define the variable. It is just a variable declaration . No memory is allocated for an extern
variable declaration. The func
variable is actually defined in 1.c
and that is where memory is allocated. You are free to use extern
declarations in as many files ( for eg 3.c
) as you need.
Note: Careful when adding extern
to header file as in accepted answer. That makes variable visible, in which ever source file the header in included and so a potential risk of name collisions or unintentional modifications.
This is an example about using function pointers...
#include <stdio.h>
void prev(int x)
{
printf( "%d\n", x-1 );
}
void next(int x)
{
printf( "%d\n", x+1 );
}
typedef void (*my_func_ptr_T)(int);
int main()
{
my_func_ptr_T foo;
foo = &prev;
foo( 5 );
return 0;
}
You can run the code in this DEMO
You make the variable func
known in file 2.c:
// file 2.c
extern my_func_ptr_T func;
void do_callback() {
// i want to do this
func(1,2);
}
By declaring func
as extern
you tell the compiler that this particular variable will live in a file / different compilation unit (eg 1.o compiled from 1.c, where a variable of the same name and type is declared without the extern
keyword), and it does not need to create it when compiling 2.c into 2.o.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.