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

31,203

Solution 1

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;

Solution 2

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.

Share:
31,203
user1106072
Author by

user1106072

Updated on July 05, 2022

Comments

  • user1106072
    user1106072 almost 2 years

    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.

    it looks like this:

    void (*current_menu)(int);
    

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

  • Drew Dormann
    Drew Dormann over 12 years
    Very true! function<void(int)> is also available if you have access to boost or C++11.
  • Dave
    Dave over 12 years
    the ampersand isn't strictly necessary
  • Drew Dormann
    Drew Dormann over 12 years
    That is true, @Dave. In C, it's a stylistic choice of mine for clarity. In C++ it's sometimes required in certain template contexts, so I just do it for consistency.
  • Geremia
    Geremia almost 9 years
    @DrewDormann I thought extern was redundant. Shouldn't it be globally visible without specifying extern?
  • Drew Dormann
    Drew Dormann almost 9 years