Search code examples
cc++11pointersfunction-pointersextern

Function pointer usage with hierarchical control: xtern/namespace C++


Below is a sample usage from an older and newer version of a software stack. How would the function usage and access differ with the hierarchical structuring of the two pieces of code below:

namespace std
{
    typedef void (*function)();
    extern "C" function fn_ptr(function) throw();
}

And

extern "C++" 
{
  namespace std
  {
      typedef void (*function)();
      function fn_ptr(function) throw();
  }
}

The first one is easy but I wish to access fn_ptr from both C and C++ based files in the 2nd example. Note that it is extern "C++" and there isn't much to find about extern "C++" usage on Stackoverflow or Google.


Solution

  • Here is the unique approach to accessing a function defined in C++ from C. extern "C++" is implicit by default in standard.

    Let us assume that you have a .c file (FileC.c) and you wish to call a function defined in .cpp (FileC++.cpp). Let us define the function in C++ file as:

    void func_in_cpp(void) 
    { 
      // whatever you wanna do here doesn't matter what I am gonna say!
    }
    

    Do the following steps now (to be able to call the above function from a .c file):

    1) With you regular C++ compiler (or www.cpp.sh), write a very simple program that includes your function name (func_in_cpp). Compile your program. E.g.

    $ g++ FileC++.cpp -o test.o
    

    2) Find the mangled name of your function.

    $ nm test.out | grep -i func_in_cpp
    [ The result should be "_Z11func_in_cppv" ]
    

    3) Go to your C program and do two things:

    void _Z11func_in_cppv(void);  // provide the external function definition at the top in your program. Function is extern by default in C.
    
    int main(void) 
    {
        _Z11func_in_cppv();   // call your function to access the function defined in .cpp file
    }