Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 receive a function pointer as its second argument.

extern "C"
{
void uponSignal(int);
}

void uponSignal(int)
{
    // set some flag to quit the program
}

static
void installSignalHandler()
{
    // initialize the signal handler
    static struct sigaction sighandler;
    memset( &sighandler, 0, sizeof(struct sigaction) );
    sighandler.sa_handler = uponSignal;

    // install it
    sigaction( SIGINT, &sighandler, nullptr );
}

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

Bonus question: can uponSignal be declared static?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
649 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...