public inbox for gcc-help@gcc.gnu.org
 help / color / mirror / Atom feed
* Correct way to provide a C callback function nside C++
@ 2023-01-27 13:23 Pepe
  2023-01-27 13:48 ` Tom Kacvinsky
  2023-01-27 14:07 ` Jonathan Wakely
  0 siblings, 2 replies; 7+ messages in thread
From: Pepe @ 2023-01-27 13:23 UTC (permalink / raw)
  To: gcc-help

Hi there,

I’m in an ongoing discussion about whether or not one should use extern “C” when defining a function that will be used as a callback in a statically linked C library. For example:

c_func.h:
// …
void reg_callback(void (*fn)());
// …

cpp_impl.cpp:
// …
extern “C” {
#include “c_func.h”
}

// my callback function with internal linkage
namespace {

extern “C” {
static void my_callback_A() {
	// …
}
} // extern “C”

void my_callback_B() {
	// …
}

} // namespace

void do_something() {
	reg_callback(my_callback_A);
	reg_callback(my_callback_B);
}

Both callbacks have internal linkage. Both work fine, and something like my_callback_B is found in lots of code bases.

In my opinion, using callback B is implementation defined behaviour, because it is not guaranteed that C and C++ use the same calling conventions. Therefore a function must adhere to the C calling conventions to be used as a callback in a C library, which would be callback A.

I’ve been trying to find something definitive for days now, but to no avail. Now I’m not sure what’s true or not. The counter argument is the following: The compiler should know reg_callback is a C function and make sure that a given argument would either be valid or cause a compiler error. That sounds reasonable, so I would love to know how to do it properly for future reference. Given we use gcc I was hoping to get a definitive answer in this mailing list. Thanks a lot!

Pepe

^ permalink raw reply	[flat|nested] 7+ messages in thread

end of thread, other threads:[~2023-01-27 15:32 UTC | newest]

Thread overview: 7+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2023-01-27 13:23 Correct way to provide a C callback function nside C++ Pepe
2023-01-27 13:48 ` Tom Kacvinsky
2023-01-27 13:51   ` Jonathan Wakely
2023-01-27 14:07 ` Jonathan Wakely
2023-01-27 14:29   ` Michael Pape
2023-01-27 14:30   ` Xi Ruoyao
2023-01-27 15:32     ` Jonathan Wakely

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).