Share via

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

jinwook GIm 1 Reputation point
2021-08-04T11:37:45.31+00:00

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.

Developer technologies | C++
Developer technologies | C++

A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.


2 answers

Sort by: Most helpful
  1. jinwook GIm 1 Reputation point
    2021-08-05T00:15:00.573+00:00

    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.

    0 comments No comments

  2. WayneAKing 4,936 Reputation points
    2021-08-04T20:52:34.387+00:00

    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
    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.