Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 768
user1106072 Avatar asked Dec 19 '11 14:12

user1106072


People also ask

Can you write functions in a header file C?

The answer to the above is yes. header files are simply files in which you can declare your own functions that you can use in your main program or these can be used while writing large C programs. NOTE:Header files generally contain definitions of data types, function prototypes and C preprocessor commands.

How can a function pointer be declared?

You can use a trailing return type in the declaration or definition of a pointer to a function. For example: auto(*fp)()->int; In this example, fp is a pointer to a function that returns int .


1 Answers

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;
like image 117
Drew Dormann Avatar answered Oct 27 '22 09:10

Drew Dormann