[英]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.h
和1.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.