C linkage for function pointer passed to C library

后端 未结 2 1476
春和景丽
春和景丽 2020-12-20 16:53

My case is pretty simple: I want my C++ program to deal with Unix signals. To do so, glibc provides a function in signal.h called sigaction, which expects to re

2条回答
  •  [愿得一人]
    2020-12-20 17:23

    My question is: is the extern "C" linkage specifier necessary?

    For maximum portability, yes; the C++ standard only guarantees interoperability with C via functions declared extern "C".

    Practically, no; most sensible ABIs (including the GNU ABI used by glibc) will use the same calling convention for C and C++ non-member (and static member) functions, so that extern "C" is only needed to share the function name between languages.

    Bonus question: can uponSignal be declared static?

    Yes. External linkage is only needed to access the function by name from other translation units; it's not necessary to call the function via a function pointer.

提交回复
热议问题