How to declare function pointer in header and c-file?

后端 未结 3 1166
清歌不尽
清歌不尽 2020-12-31 02:12

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 wan

相关标签:
3条回答
  • 2020-12-31 02:43

    It's often helpful to use typedef with function pointers, so you can name the type to something descriptive:

    typedef void (*MenuFunction)(int);
    

    Then you would have a global variable of this type, probably in menus.c, and declared (with extern) in menus.h:

    static void my_first_menu_function(int x)
    {
      printf("the menu function got %d\n", x);
    }
    
    MenuFunction current_menu = my_first_menu_function;
    

    From main.c, you can then do:

    #include "menu.h"
    
    current_menu(4711);
    

    to call whatever function is currently pointed at by current_menu.

    0 讨论(0)
  • 2020-12-31 02:44

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

    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.

    In a header:

    extern void (*current_menu)(int);
    

    In one source file:

    void (*current_menu)(int) = &the_func_i_want;
    
    0 讨论(0)
  • 2020-12-31 02:53

    A pointer function itself does not have a function definition. It's nothing more than a pointer to a type, the type being specified by the return type of the function and the parameter list. What you need to do is define a function with the same parameter list and return type, then use your pointer function to hold that function's address. You can then call the function through the pointer.

    0 讨论(0)
提交回复
热议问题