我是 C++ 新手。我正在做的是用 C 创建一个回调库文件。该文件将在 C++ 应用程序中使用。 C 文件将只有三个函数,仅供引用,由于类开销,我不想为此创建另一个 cpp 文件/类,并且类也应该仅在 cpp 文件中。请查看代码片段。 C 文件 XYZ.c 在其函数中使用 ABC.hpp 类。
Allheader.hpp
#include<iostream>
.
.
ABC.hpp
#include "Allheader.hpp"
.
.
XYZ.h
func1();
func2();
func3();
XYZ.c
include "XYZ.h"
include "ABC.hpp"
func1()
{
using class of ABC here
}
func2() {}
func3() {}
MyApplication.cpp
extern "C" { #include "XYZ.h"}
.
.
因此此文件 XYZ.c/XYZ.h 将在我的 CPP 应用程序中用作回调。
使用 g++ 编译
我做了什么。
- 已编译:显示错误,没有文件 iostream。
当我编译 C 文件并在其中使用 C++ 时,开始使用 __BEGIN_DECLS
XYZ.c 文件中的代码位于
__BEGIN_DECLS __END_DECLS
同事建议的阻止。但还是报错 是一样的。
如何在 C 函数中使用 C++?请提出任何解决方案。
最佳答案
您无法将 C++ 代码编译为 C 代码。此 C 代码无效:
#include "XYZ.h"
#include "ABC.hpp" // this is wrong
func1()
{
using class of ABC here // this is also wrong (and incomplete...)
}
func2() {}
func3() {}
再说一次 - 你根本不能那样做。 C 和 C++ 是不同的语言。你不妨尝试问“为什么我不能用 C 编译器编译 Java 或 Python”,答案是一样的,“因为它不是 C。”
您可以通过 C 中的 extern "C"
链接调用 C++ 函数。
来自 C++ 文件:
extern "C" void calledFromC()
{
// C++ code
}
然后,在可由 C 进行 #include
的 C++ header 中:
#ifdef __cplusplus
extern "C" {
#endif
void calledFromC();
#ifdef __cplusplus
}
#endif
关于c++ - 在 C 中使用 C++ 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53556415/