如何在头文件和c文件中声明函数指针? [英] How to declare function pointer in header and c-file?

查看:113
本文介绍了如何在头文件和c文件中声明函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对如何在头文件中声明函数指针有点困惑.我想在 main 和一个名为 menus.c 的文件中使用它,并在我假设的 menus.h 中声明它.我们要初始化指向某个函数.

I'm a little confused over how to declare a function pointer in a header file. I want to use it in main and a file called menus.c and declare it in menus.h I assume. We want to initialize to point to a certain function.

看起来像这样:

void (*current_menu)(int);

我们在 menus.c、menus.h 和 main 中写了什么?

What do we write in menus.c, menus.h and main?

推荐答案

函数指针仍然是指针,也就是说它仍然是变量.

A function pointer is still a pointer, meaning it's still a variable.

如果您希望一个变量在多个源文件中可见,最简单的解决方案是在标题中声明它extern,并在其他地方定义.

If you want a variable to be visible from several source files, the simplest solution is to declare it extern in a header, with the definition elsewhere.

在标题中:

extern void (*current_menu)(int);

在一个源文件中:

void (*current_menu)(int) = &the_func_i_want;

这篇关于如何在头文件和c文件中声明函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆