3.15 Passing a reference between C and C++

When calling a C function from C++, declare the function using extern "C". When calling a C++ function from C, declare the function using extern and define it as extern "C".

To pass references between C and C++:

Procedure

  1. Use the extern "C" declaration for the C function. Also, define the C++ function as extern "C" to specify that the function has C linkage. For example:
    // Declaration of the C function to be called from C++
    extern "C" int cfunc(const int&); 
    extern "C" int cppfunc(const int& r) {
        // Definition of the C++ function to be called from C.
        return 7 * r;
    }
    int f() {
        int i = 3;
        return cfunc(i);    // passes a pointer to 'i'
    }
    
  2. In the C function, declare the C++ reference with extern. For example:
    /* declaration of the C++ function to be called from C */
    extern int cppfunc(const int*);    
    int cfunc(const int *p) {       
        /* definition of the C function to be called from C++ */
        int k = *p + 4;
        return cppfunc(&k);
    }
    
Non-ConfidentialPDF file icon PDF versionARM DUI0471M
Copyright © 2010-2016 ARM Limited or its affiliates. All rights reserved.