Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Calling C++ functions from C

Status
Not open for further replies.

Andrea268

Programmer
Dec 31, 2002
1
US
Hello everyone,

I'm trying to call a C++ function from C. The problem is that when I call it from my main function in main.c, it works. But when I call it from a procedure other than main defined in some other c file, the arguments get messed up. Here's my setup.

//Inside Foo.cpp

extern "C"
{
int foo(int a, int b) //The fcn I'm trying to call
{
return a + b;
}
}


//Inside main.c

extern int foo(int a, int b);

int main(int argc char** argv)
{

foo(1, 2); //This works
}

//Inside SomeotherCfile.c

extern int foo(int a, int b);

int callfoo(int a, int b)
{
foo(a, b); //This doesn't work. The parameters
//a and b get mangled.
}

Can anyone tell me why is it that when foo is called from my main routine in main.c, it works. But when it is called from any other procedure in a different .c file, the parameters get messed up? I've defined foo as extern "C", so shouldn't that indicate to the compiler to use C calling conventions?

Thank you for your time.

Andrea
 
C doesn't know anything about C++ but C++ knows about C. I don't really know why it works in main.

The easiest way around it is to give all your files a C++ extension, whether or not they are C and compile the whole lot as C++. That way, everything is consistent and you won't get any link problems.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top