我有一个 C++ 文件及其头文件。我需要在 C 代码中包含此头文件并使用其中的函数。
通过main.c
编译cpp.h
文件时,由于C++链接而编译失败。
使用宏__cplusplus
stream
和string
未解析,是否有某种方法可以编译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/