2016-04-28 63 views
0

我有交流和CPP文件混合C++字符串使用C

mycpp.cpp

fun() 
{ 
//code goes here.... 
} 

mycpp.h

#include<string> 
struct str{ 
std::string a; 
}; 
func(); 

myc.c

#include "mycpp.h" 

func(); 
//with other c codes.. 

这是大型代码清单的一部分。所以它通过C++和c编译。 我的问题是,当mycpp.h通过myc.c(包含在myc.c)编译,编译器会引发错误说致命错误:字符串:没有这样的文件或目录

有一些包装机制克服这种情况?

+1

检查[this](http://stackoverflow.com/a/16058799/4790490),它可能会有所帮助。 – Hearty

+2

你在C中包含C++结构,你期望什么?他们是不同的语言,当然这是行不通的。 – Leandros

+0

您不能混用2种语言。您可以使用标准C++编译器(如g ++)编译C,但反之亦然。 – FrenchFalcon

回答

4

您不能在C文件中包含C++头文件。

用C链接声明函数func(),并将其称为C文件内的外部函数。

实施例:

mycpp.cpp

void func(void) 
{ 
    /* foo */ 
} 

mycpp.h

extern "C" void func(void); 

myc.c

extern void func(void); 

/* you can now safely call `func()` */ 

你不能在C中使用std::string,如果你想访问你的字符串,你必须将它传递给你的C代码,通过传递一个char const*与字符串的内容。您可以通过拨打std::string::c_str()访问此字符串。你可以阅读更多关于c_str()here