0

Suppose I have the following code, is something like that possible to do? I mean passing a variable that is inside a c++ object to a function.

In foo.hpp

class foo
{
    public :

    int a;
}

in main.cpp

#include "cfile.h"
#include "foo.hpp"

void main()
{

    foo * fooPtr = new foo();
    int RetVal = MyCfunc(fooPtr->a);
}

In cfile.c

#include "cfile.h"

int MyCfunc(int var)
{

    var + = 1;
    return var;
}
Werner Henze
  • 16,404
  • 12
  • 44
  • 69
Fluffy
  • 337
  • 1
  • 5
  • 16
  • `var + = 1;` does not compile. You meant to write `return var+1`; I wonder why you are attempting to increment `var` in `MyCfunc`. Are you hoping to modify the value in a way that is visible to the caller? – David Heffernan Jul 08 '13 at 09:55
  • Also, there is no `void main` in the world, there are only `int main()`, or `int main(int argc, char *argv[])` – billz Jul 08 '13 at 10:01

2 Answers2

3

Technically this compiles (well, after fixing various syntactic issues that have been pointed out already), but you have to be careful. You need to make sure everything can link (i.e. symbols are created correctly for both, C and C++ source code); I usually use g++ as a compiler which, for C files, works fine. Second, you have to make sure to tell your C++ code that you want to reference C code. Therefore, in your "cfile.h" you want to add

#ifdef __clpusplus
extern "C" {
#endif

 // your C include file

#ifdef __cpluspus
}
#endif

That ensures that you can include your C include file into C++ sources, while telling the C++ compiler to use C style name mangling when compiling the code. Then go ahead and compile with C and C++ files, and link them into an executable:

g++ -g -O0 -o test main.cpp cfile.c

There is more about this here: Combining C++ and C - how does #ifdef __cplusplus work?

Community
  • 1
  • 1
Jens
  • 8,423
  • 9
  • 58
  • 78
1

It would be better if you supplied an actual sample of what you're trying to do. As other have pointed out, the code you supplied has a number of syntax problems and passing basic types between C & C++ is mostly never a problem. An int is an int everywhere (as long as you aren't crossing 32/64 bit boundaries).

Where you can get into trouble is calling C/C++ functions/methods from the other side or passing classes around (use pointers and only pass them, usually, when in C code).

MichaelH
  • 380
  • 1
  • 7