Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include and compile C++ header file from C

Tags:

c++

c

I have a C++ file and its header file. I need to include this header file in a C code and use the functions in it.

When the cpp.h file is compiled through main.c, compilation fails because of the C++ linkage.

On using the macro __cplusplus stream and string are not resolved, is there some way to compile the cpp.h file through and execute?

I have given a outline of my code only.

C++ header file 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++ file cpp.cpp:

c1::fun1(s2 &s3)
{
 fstream file;

}

c1::fun2(std::string &x,const char *y)
{

}

C file main.c:

#include "cpp.h"
void main()
{
 c1 c2;
 s1 structobj;
 c2.fun1(&structobj);
 printf("\n value of a in struct %s",structobj.a);

}
like image 571
Sathiya Avatar asked Mar 10 '26 05:03

Sathiya


2 Answers

Basically, you can't. You need to put only C functions in your header file. You put them in a extern "C" block this way:

#ifdef __cplusplus
extern "C"
{
#endif

extern void myCppFunction(int n);

#ifdef __cplusplus
}
#endif

The extern "C" block is not recognized by a C compiler, but the C++ compiler need it to understand he have to consider functions inside as C functions.

In your cpp file you can define myCppFunction() so that she uses any C++ code, you will get a function C code can use.

Edit: I add a full example of how to link a program with a C main() using some C++ functions in a module.

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;
}

Compiling and linking:

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

You cannot link such a program with gcc. If you want to link with gcc you need to put all the C++ code in a shared library, I don't put an example as it would be a bit platform dependent.

like image 145
jdarthenay Avatar answered Mar 11 '26 19:03

jdarthenay


This can be done by introducing a wrapper to c++ function. The C function calls the wrapper function which inturn calls the desired C++ function (including member functions). More details are available here

like image 31
Sathiya Avatar answered Mar 11 '26 19:03

Sathiya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!