question

jinwookGIm-2105 avatar image
0 Votes"
jinwookGIm-2105 asked jinwookGIm-2105 answered

using both c/c++ codes, float returning C++ function doesn't work in C code

I'm using both c/c++ codes in VS2019
And float returning C++ function doesn't work in C code.

//C++ code
extern "C" float cppfunc()
{
return 1.0f;
}

//C code
void cfunc()
{
float val = cppfunc();
PRINT(val); // actually I look up the variable with debugger, And It seems like 21210656.0
}

I need some help.

c++
· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Can you show us a real example project that anyone can try to build to reproduce this issue?

0 Votes 0 ·

It seems that you haven't provided a declaration for cppfunc in your C program. Absent a declaration, C compiler assumes int return value (whereas C++ compiler complains; C++ doesn't allow calling undeclared functions). So basically the caller takes whatever random garbage happens to be sitting in EAX register after cppfunc returns, and assumes it to be the function's return value (the actual return value is sitting on the FPU register).

0 Votes 0 ·

Thank you guys. How brilliant you are.

0 Votes 0 ·
jinwookGIm-2105 avatar image
0 Votes"
jinwookGIm-2105 answered

IgorTandetnik-1300 avatar image IgorTandetnik-1300 · 10 hours ago
It seems that you haven't provided a declaration for cppfunc in your C program. Absent a declaration, C compiler assumes int return value (whereas C++ compiler complains; C++ doesn't allow calling undeclared functions). So basically the caller takes whatever random garbage happens to be sitting in EAX register after cppfunc returns, and assumes it to be the function's return value (the actual return value is sitting on the FPU register).

0 Votes0 · Reply More

It works. I appreciate you.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

WayneAKing-0228 avatar image
0 Votes"
WayneAKing-0228 answered

Try the following and see if it does what you are attempting.

(1) Create a Win32 Console project.

(2) Add a C source code file to the project, with this code:

 /* C_Code.c */
 #include <stdio.h>
    
 extern float cppfunc();
    
 void cfunc()
 {
     float val = cppfunc();
     printf("%f\n", val);
 }

(3) Add a C++ source code file to the project, with this code:

 // CPP_Code.cpp
 #include <iostream>
    
 extern "C" void cfunc();
    
 extern "C" float cppfunc()
 {
     return 1.0f;
 }
    
 int main()
 {
     std::cout << cppfunc() << "\n";
     cfunc();
 }

(4) Build and Run.

Expected output:

1
1.000000

  • Wayne

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.