static vs extern “C”/“C++”

前端 未结 5 1695
伪装坚强ぢ
伪装坚强ぢ 2020-11-29 03:23

What is the difference between a static member function and an extern \"C\" linkage function ? For instance, when using \"makecontext\" in C++, I need to pass a pointer to f

5条回答
  •  伪装坚强ぢ
    2020-11-29 04:12

    Most of what extern "C" does is largely compiler dependant. Many platforms change the name mangling and calling convention based off the declaration, but none of that is specified by the standard. Really the only thing the standard requires is that the code in the block is callable from C functions. As for your specific question, the standard says:

    Two function types with different language linkages are distinct types even if they are otherwise identical.

    This means extern "C" void proxy(int i) {} and /*extern "C++"*/void proxy(int i) {} have different types, and as a result pointers to these functions would have different types as well. The compiler doesn't fail your code for the same reason it wouldn't fail a great piece of work like:

    int *foo = (int*)50;
    makecontext(..., (void (*)(void)) foo, ...);
    

    This code might work on some platform, but that doesn't mean it will work on another platform (even if the compiler was fully standard compliant). You are taking advantage of how your particular platform works, which might be ok if you aren't concerned about writing portable code.

    As for static member functions, they aren't required to have a this pointer so the compiler is free to treat them as a non member function. Again, the behavior here is platform specific.

提交回复
热议问题