Problem
I want to define two functions with the same name in different header files, such that:
A) Each function can be called by a C++ program (using namespaces to avoid conflicts).
B) The functions can be used with Python ctypes, which requires extern "C" to prevent name mangling.
While A is easily achievable using namespaces, B requires extern "C", which discards the C++ namespace information, resulting in a redefinition error during compilation.
Example:
one.h
namespace one{
extern "C" void free(void *ptr);
}
two.h
namespace two{
extern "C" void free(void *ptr);
}
This works fine in C++ code using namespaces to differentiate between one::free() and two::free(). However, when I add extern "C" to make the functions accessible from Python ctypes, I get a compiler error due to redefinition.
Workaround
I know I could use unique function names for each function, but I’m looking for a way to use the same function name for both C++ and Python ctypes.
Is there a way to have the same function name in different header files, accessible by both Python ctypes and C++ library calls, without causing this redefinition error?
import lib1andimport lib2, and thenlib1.free lib2.free? Then there shouldn't be the problem with redefinitions because you don't need to link the 2 libs together?