繁体   English   中英

使用在其他源文件中初始化的函数指针

[英]Use function pointer initialized in other source file

我有函数指针,在文件1.h中声明如下

// file : 1.h
typedef void (*my_func_ptr_T)(int , int);

在文件1.c中,我创建了一个全局实例并对其进行了初始化

// file 1.c
my_func_ptr_T func;

void callback (my_func_ptr_T _ptr) {
    func = _ptr;
}

现在,我如何在另一个文件说2.c中使用此功能ptr'func'

// file 2.c 
void do_callback() {
    //  i want to do this
    func(1,2);
}

检查以下更改

// 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

2.c更改为以下将有所帮助。 离开1.h1.c不变。

#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( );
}

重要的是要理解,关键字extern不会定义变量。 它只是一个变量声明 没有为extern变量声明分配内存。 func变量实际上是在1.c 定义的,这就是分配内存的位置。 您可以根据需要在任意多个文件(例如3.c )中自由使用extern声明。

注意:将extern添加到头文件中时要小心,如接受的答案中所述。 这样就可以看到变量,无论在哪个源文件中都包含标头,因此存在潜在的名称冲突或无意修改的风险。

这是有关使用函数指针的示例...

 #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;
 }

您可以在此DEMO中运行代码

您使变量func在文件2.c中已知:

// file 2.c
extern my_func_ptr_T func;

void do_callback() {
//  i want to do this
    func(1,2);
}

通过将func声明为extern您可以告诉编译器该特定变量将存在于文件/不同的编译单元中(例如,从1.c编译的1.o,其中声明了具有相同名称和类型的变量而没有extern关键字),并且在将2.c编译为2.o时不需要创建它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM