c++ - 从 C 包含并编译 C++ 头文件

标签 c++ c

我有一个 C++ 文件及其头文件。我需要在 C 代码中包含此头文件并使用其中的函数。

通过main.c编译cpp.h文件时,由于C++链接而编译失败。

使用宏__cplusplus streamstring未解析,是否有某种方法可以编译cpp.h 文件通过并执行?

我只给出了我的代码的概要。

C++ 头文件cpp.h:

struct s1
{
string a;
string b;
};
typedef struct s1 s2;
class c1
{
public:
void fun1(s2 &s3);
private: 
fun2(std::string &x,const char *y);
};

C++ 文件cpp.cpp:

c1::fun1(s2 &s3)
{
 fstream file;

}

c1::fun2(std::string &x,const char *y)
{

}

C 文件main.c:

#include "cpp.h"
void main()
{
 c1 c2;
 s1 structobj;
 c2.fun1(&structobj);
 printf("\n value of a in struct %s",structobj.a);

}

最佳答案

基本上,你不能。 您只需将 C 函数放入头文件中。 您可以这样将它们放入 extern "C" block 中:

#ifdef __cplusplus
extern "C"
{
#endif

extern void myCppFunction(int n);

#ifdef __cplusplus
}
#endif

C 编译器无法识别 extern "C" block ,但 C++ 编译器需要它来理解他必须将内部函数视为 C 函数。

在你的cpp文件中你可以定义myCppFunction(),这样她使用任何C++代码,你都会得到一个C代码可以使用的函数。

编辑:我添加了一个完整的示例,说明如何使用模块中的一些 C++ 函数将程序与 C main() 链接。

stackoverflow.c:

#include "outputFromCpp.h"

int main()
{
    myCppFunction(2000);

    return 0;
} 

outputFromCpp.h:

#ifndef OUTPUT_FROM_CPP_H
#define OUTPUT_FROM_CPP_H

#ifdef __cplusplus
extern "C"
{
#endif

extern void myCppFunction(int n);

#ifdef __cplusplus
}
#endif

#endif

outputFromCpp.cpp:

#include "outputFromCpp.h"

#include <iostream>

using namespace std;

void myCppFunction(int n)
{
    cout << n << endl;
}

编译和链接:

gcc -Wall -Wextra -Werror -std=gnu99 -c stackoverflow.c
g++ -Wall -Wextra -Werror -std=c++98 -c outputFromCpp.cpp
g++ -o stackoverflow.exe stackoverflow.o outputFromCpp.o -static

您不能将这样的程序与 gcc 链接。 如果您想与 gcc 链接,您需要将所有 C++ 代码放入共享库中,我不提供示例,因为它有点依赖于平台。

关于c++ - 从 C 包含并编译 C++ 头文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36806671/

相关文章:

c++ - Cuda 数学与 C++ 数学

c++ - 是否有任何内置函数来检查给定的两个数字在给定整数数组中的顺序是否相同?

c++ - 如何在 C++ 中访问 boost::python::tuple 的元素?

c++ - 类 C 结构中自动字段重新排序的方法

c - 该数组如何初始化为零?

c++ - 算术/赋值运算符和复合赋值运算符是否在C++中独立定义

c++ - 将数组的地址传递给 C++ 中的函数

c - while ((c = getchar()) != EOF) 不终止

python - SWIG C/python 和无符号字符指针

c - *nix mkfifo : Is it possible to modify metadata (i. e.上一次更改)