M
Mark A. Gibbs
I have a question about mixing C and C++.
In a C++ translation unit, I want to define a function with internal
linkage and C calling convention. Here's a sample of what I want to do:
// main.cpp
// This is defined in a C module
extern "C" void fake_qsort(void*, std::size_t, std::size_t,
int (*compare)(const void*, const void*));
namespace {
int compare_func_(const void*, const void*);
} // anonymous namespace
int main()
{
foo bunch_of_foos[100];
// ... fill bunch_of_foos somehow
// Fake qsort has the same signature as std::qsort
// but is extern "C"
fake_qsort(&bunch_of_foos, sizeof(bunch_of_foos), sizeof(foo),
compare_func_);
return 0;
}
int compare_func_(const void*, const void*)
{
// ...
}
In a C++ translation unit, compare_func_() will have C++ calling
convention by default, unless I explicitly declare it extern "C". And
the fake_qsort() function is expecting a function with C calling convention.
I know this is illegal:
extern "C" static int compare_func_(const void*, const void*);
And this *seems* to be legal:
namespace {
extern "C" int compare_func_(const void*, const void*);
} // anonymous namespace
But does it do what I want (give me a function with internal linkage but
C calling convention)?
What about this?
extern "C" {
static int compare_func_(const void*, const void*);
}
Or even this?
extern "C" {
namespace {
int compare_func_(const void*, const void*);
} // anonymous namespace
}
Mark
In a C++ translation unit, I want to define a function with internal
linkage and C calling convention. Here's a sample of what I want to do:
// main.cpp
// This is defined in a C module
extern "C" void fake_qsort(void*, std::size_t, std::size_t,
int (*compare)(const void*, const void*));
namespace {
int compare_func_(const void*, const void*);
} // anonymous namespace
int main()
{
foo bunch_of_foos[100];
// ... fill bunch_of_foos somehow
// Fake qsort has the same signature as std::qsort
// but is extern "C"
fake_qsort(&bunch_of_foos, sizeof(bunch_of_foos), sizeof(foo),
compare_func_);
return 0;
}
int compare_func_(const void*, const void*)
{
// ...
}
In a C++ translation unit, compare_func_() will have C++ calling
convention by default, unless I explicitly declare it extern "C". And
the fake_qsort() function is expecting a function with C calling convention.
I know this is illegal:
extern "C" static int compare_func_(const void*, const void*);
And this *seems* to be legal:
namespace {
extern "C" int compare_func_(const void*, const void*);
} // anonymous namespace
But does it do what I want (give me a function with internal linkage but
C calling convention)?
What about this?
extern "C" {
static int compare_func_(const void*, const void*);
}
Or even this?
extern "C" {
namespace {
int compare_func_(const void*, const void*);
} // anonymous namespace
}
Mark