c++ - 如何使用对 C 函数和类对象的外部调用来处理 C++ 头文件
问题描述
我正在尝试编译一个涉及 C 和 C++ 文件的应用程序。对于一个特定的标题,我遇到了问题。有问题的文件(C++ 头文件)看起来像这样:
#ifndef TASK_H
#define TASK_H
#include "MyCCPObject.h"
int foo1(int);
int foo2(int);
int fooObject(MyCCPObject myCppObject); // Function involves a Class "MyCCPObject" type
#ifdef __cplusplus
extern "C" {
#endif
int foo3(void); // Function called in a C file
#ifdef __cplusplus
}
#endif
#endif //TASK_H
我有一个函数fooObject()
,它有一个MyCCPObject
类类型作为参数。此外,其中一个函数foo3()
将从 C 文件中调用。当 C 编译器编译此标头时,我收到以下错误: "error: #20:identifier "class" is undefined"
. 为了避免这种情况,我不得不:
- 将
fooObject()
声明放在编译器保护中:
#ifdef __cplusplus
int fooObject(MyCCPObject myCppObject);
#endif
- 将编译器保护也放在头文件的类声明中
MyCCPObject.h
:
#ifdef __cplusplus
class MyCCPObject
{
public:
MyCCPObject(uint32_t val);
private:
uint32_t value;
};
#endif
注意:MyCCPObject
不会在任何 C 文件中调用。那么,当我有一个 C++ 头文件时,什么是更好的方法,其中涉及:
- 函数将涉及一个类对象
extern
调用 C文件
解决方案
为 C 和 C++ 代码使用单独的标头。
将foo3
声明(包括__cplusplus
守卫)移动到单独的标题中。我们称之为Foo3.h
你现在有以下文件:
Task.h
- 包含 and 的声明foo1
,foo2
并且fooObject
包括MyCCPObject.h
Foo3.h
- 包含声明foo3
Task.cpp
- 包括Task.h
并且Foo3.h
提供 和foo1
的foo2
定义foo3
App.c
- 包括Foo3.h
和使用foo3
在您的构建系统(make、cmake 等)中,在构建 C++ 库时,添加文件Task.h
、、Foo3.h
(Task.cpp
以及与 相关的其他文件MyCCPObject
)
构建 C 应用程序时,仅添加Foo3.h
和App.c
. 这样,其他头文件(包含 C++ 代码)将不会被编译,因此不会给出任何错误。
推荐阅读
- html - 为什么没有出现 Django 表单集?
- python - Culebra 测试仪错误:没有名为 culebratester_client.api.default_api 的模块
- excel - 确保用户在大写字母的输入框中输入文本
- botframework - Botbuilder 4. 一个应用服务上的机器人很少
- java - 使用 GSON 和 lambda 过滤 JSON
- python - Holoviews .to 接口:如何根据输入参数对 cmap 和范围进行属性化
- swift - 如何让 macOS 将删除的 .stl 文件呈现为 public.standard-tesselated-geometry-format?
- c# - C#如何通过对象和线程以编程方式记录内存
- arduino - 使用 FastLED 库为板 Arduino/Genuino Mega 或 Mega 2560 编译时出错
- javascript - 在 Jquery Datepicker 中检查日期范围