从C

时间:2016-04-23 04:34:04

标签: c++ c

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

通过cpp.h编译main.c文件时,由于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);

}

2 个答案:

答案 0 :(得分:3)

基本上,你不能。 您只需要在头文件中放置C函数。 你以这种方式将它们放在extern "C"块中:

#ifdef __cplusplus
extern "C"
{
#endif

extern void myCppFunction(int n);

#ifdef __cplusplus
}
#endif

C编译器无法识别extern "C"块,但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 ++代码放在一个共享库中,我不会举一个例子,因为它会有点依赖于平台。

答案 1 :(得分:1)

这可以通过向c ++函数引入包装器来完成。 C函数调用包装函数,该函数调用所需的C ++函数(包括成员函数)。 有关详细信息,请here

相关问题