0

I have a c and cpp file

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..

This is a part of large code list. So it gets compiled via c++ and c. My problem is when mycpp.h is compiled through myc.c (which is included in myc.c) , Compiler throws an error saying fatal error: string: No such file or directory

Is there some wrapper mechanism to overcome this scenario?

Nerdy
  • 1,016
  • 2
  • 11
  • 27

1 Answers1

4

You cannot include a C++ header file in a C file.

Declare the function func() with C linkage, and refer to it as an extern function inside your C file.

Example:

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()` */

You cannot use std::string in C, if you want to access your string, you have to pass it accordingly into your C code, by passing it a char const* with the contents of the string. You can get access to this string by calling std::string::c_str(). You can read more about c_str() here.

Leandros
  • 16,805
  • 9
  • 69
  • 108