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?
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. )
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
}
精彩评论