【问题标题】:Mixing c++ string with c将c ++字符串与c混合
【发布时间】:2016-04-28 07:35:42
【问题描述】:

我有一个 c 和 cpp 文件

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 中)编译时,编译器抛出一个错误说 fatal error: string: No such file or directory

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

【问题讨论】:

  • 检查this,它可能会有所帮助。
  • 您在 C 中包含 C++ 结构,您期望什么?它们是不同的语言,当然不行。
  • 您不能混合使用 2 种语言。您可以使用标准 c++ 编译器(例如 g++)编译 C,但反之则不行。
  • 如果您能向我们展示一下为什么首先包含 mycpp.h 将会很有帮助。

标签: c++ c


【解决方案1】:

您不能在 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的信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多