0

I need to call cpp method from c file. I have written this interface for that..

cpp file

extern "C" void C_Test(int p){
      Class::CPP_Test(p);
}

c file

extern void C_Test(int p);


void C_Function(){
   C_Test(10); //error
}

I get error in c file "undefined reference to C_Test(int)"

any idea whats wrong?

Meloun
  • 13,601
  • 17
  • 64
  • 93

3 Answers3

1

You must declare extern only for function prototype, and ensure to link correctly. In addiction to this, CPP_Test(p) must be a static member of Class, otherwise your code does not work. At last, extern "C" must enclose in brackets its content, more like

extern "C"
{
  void C_Test(int p)
  {
    Class::CPP_Test(p);
  }
}

Tell us if this works.

Jepessen
  • 11,744
  • 14
  • 82
  • 149
1

Are you compiling both with a C++ compiler? C++ compilers may compile a C-source file as C++, in which case it will perform name mangling, so you need to be sure to compile the C source file with a C compiler.

chmeee
  • 3,608
  • 1
  • 21
  • 28
  • I've seen them mangle and add prefix (I think Visual Studio possibly from memory, or maybe Borland), so even if you extern "C" your function may be _C_Test(int). Look at your settings. Also check your map file to see what symbols are being exported. – Josh Petitt Aug 22 '12 at 13:27
0

I am using C++ compiler for both types of files. Without "C" it works!! Also without extern "c" it works!

Meloun
  • 13,601
  • 17
  • 64
  • 93
  • That's just confusing. You said in your question that you need to call a C++ function from C file, i.e. you are using C and C++ compilers. Now you are saying that you only use C++ compiler. What does that mean? – AnT stands with Russia Aug 30 '12 at 14:22