C++ 中的函数指针对象前向声明

发布于 2024-11-27 14:42:02 字数 128 浏览 5 评论 0原文

我在 C++ 头文件中有一组函数指针对象,我将此文件包含在主头文件中,然后尝试在另一个 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

那支青花 2024-12-04 14:42:02

您可以在主标题中执行此操作。 (假设您使用的是名为 FnPointer 的 typedef)

extern FnPointer fn;

然后在您的实现文件中

FnPointer fn;

extern 表示该变量将存在,但我稍后将在其他编译单元中为其分配空间。)

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. )

毁虫ゝ 2024-12-04 14:42:02

就像使用任何其他全局指针一样使用它们。

  • 在头文件之一中将函数指针声明为 extern
  • 将标头包含在定义变量的源文件之一中
  • 在引用该变量的所有源文件中包含标头。

第 1 步:

file.h

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

第 2 步:
file.cpp

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

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

第3步:
someOtherfile.cpp

#include "file.h" 

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

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
} 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文