C++ by-reference argument and C linkage

前端 未结 5 2132
执笔经年
执笔经年 2021-01-08 00:07

I have encountered a working (with XLC8 and MSFT9 compilers) piece of code, containing a C++ file with a function defined with C linkage and a reference argument. This bugs

5条回答
  •  渐次进展
    2021-01-08 00:54

    In many cases, but not all, a reference can be implemented with an 'auto-dereferenced' pointer. That any particular compiler treats a function with C linkage and a reference parameter this way is not guaranteed in the C++ standard, and you should treat it as an implementation detail.

    It isn't hard to write a forwarding function that takes a pointer and calls your function, if you need to do this without relying on implementation details:

    void real_f(int& n) {
      n++;
    }
    extern "C" void f(int* p) { // called from C code
      real_f(*p);
    }
    

提交回复
热议问题