首页 > 解决方案 > 如何使用对 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". 为了避免这种情况,我不得不:

  1. fooObject()声明放在编译器保护中:
#ifdef __cplusplus
int fooObject(MyCCPObject myCppObject);
#endif
  1. 将编译器保护也放在头文件的类声明中MyCCPObject.h
#ifdef __cplusplus
class MyCCPObject
{
public:
    MyCCPObject(uint32_t val);
private:
    uint32_t value;

};
#endif

注意:MyCCPObject不会在任何 C 文件中调用。那么,当我有一个 C++ 头文件时,什么是更好的方法,其中涉及:

  1. 函数将涉及一个类对象
  2. extern调用 C文件

标签: c++ccross-language

解决方案


为 C 和 C++ 代码使用单独的标头。

foo3声明(包括__cplusplus守卫)移动到单独的标题中。我们称之为Foo3.h 你现在有以下文件:

  • Task.h- 包含 and 的声明foo1foo2并且fooObject包括MyCCPObject.h
  • Foo3.h- 包含声明foo3
  • Task.cpp- 包括Task.h并且Foo3.h提供 和foo1foo2定义foo3
  • App.c- 包括Foo3.h和使用foo3

在您的构建系统(make、cmake 等)中,在构建 C++ 库时,添加文件Task.h、、Foo3.hTask.cpp以及与 相关的其他文件MyCCPObject

构建 C 应用程序时,仅添加Foo3.hApp.c. 这样,其他头文件(包含 C++ 代码)将不会被编译,因此不会给出任何错误。


推荐阅读