shadeglare
shadeglare

Reputation: 7536

Function pointer object forward declaration in C++

I have a group of function pointer objects in a header C++ file, I include this file in the main header file and then trying to use these objects in another C++ file (initialize function pointers and then use these pointers through another part of code) but I always get a "multiple defined" error. Is there a way how to declare global function pointer objects in a header file?

Upvotes: 1

Views: 1572

Answers (2)

Alok Save
Alok Save

Reputation: 206566

Just use them like any other global pointers.

  • Declare the function pointers as extern in one of the header files.
  • Include the header in one of the source file that defines the variable &
  • Include the header in all the source files that reference the variable.

Step 1:

file.h

extern Func_Pointer ptr1;  /* Declaration of the function pointer */ 

Step 2:
file.cpp

 #include "file.h"  /* Declaration is available through header */  

  /* define it here */ 
  Func_Pointer ptr1 = //some address;    

Step 3:
someOtherfile.cpp

#include "file.h" 

void doSomething(void) 
{     
    *(ptr1)(); //Use it here
} 

Upvotes: 4

Michael Anderson
Michael Anderson

Reputation: 73530

You can do this in your main header. (Assusming you're using a typedef called FnPointer)

extern FnPointer fn;

Then in your implementation file

FnPointer fn;

( extern means this variable will exist but I'm going to allocate space for it later in some other compilation unit. )

Upvotes: 4

Related Questions