...in c++
+5
A:
You mean so you can export your function from a library? extern "c" {}
Crashworks
2009-02-07 21:42:01
+13
A:
You can't. It's built into compilers to allow you overloading functions and to have functions with the same name in different classes and such stuff. But you can write functions that are mangled like C functions. Those can be called from C code. But those can't be overloaded and can't be called by "normal" C++ function pointers:
extern "C" void foo() {
}
The above function will be mangled like C functions for your compiler. That may include no change at all to the name, or some changes like a leading "_" in front of it or so.
Johannes Schaub - litb
2009-02-07 21:43:04
Just a minor nit: Such functions certainly can be called from C++ function pointers: extern "C" void foo() { printf("foo\n"); }int main() { void (*f)(); f = foo; f();}
Greg Hewgill
2009-02-07 23:03:43
I think you mean "unmangled like C functions" :-)
paxdiablo
2009-02-07 23:07:11
Pax, C compilers may mangle too. gcc for example has the "-fleading-underscore" option. i remember some guy told me macosx mangles its C names with an underscore. (i don't own macosx so i can't check :)).
Johannes Schaub - litb
2009-02-08 00:09:35
Greg, it will work generally, but it's not right. the function pointer must be a pointer that points to a function with C linkage. extern "C" typedef void funt(); int main() { funt * f = foo; f(); } note, two function types are different if they have diff linkage - even if they are otherwise not.
Johannes Schaub - litb
2009-02-08 00:13:56
You can resolve the linkage issue with __cdecl.
Crashworks
2009-02-08 07:39:17
C names are not mangled. Mangling is the term used to encode type information into the function name. Adding the '_' to the front is common and an artifact of the linker (not know as mangling).
Martin York
2009-02-08 12:27:37
No matter whether you call it mangling or name decoration, the fact remains that __stdcall C functions on MSVC get renamed from "func" to "_func@12" or similar. More info here: http://msdn.microsoft.com/en-us/library/zxk0tw93(VS.71).aspx
bk1e
2009-02-08 18:05:13
Martin York. it doesn't matter how you call it. mangling is one term, decoration is another. both change the name that is used in the object file. wikipedia has an article about it (well, in some parts, it contradicts against itself..., but it contains the decoration stuff). i agree with bk1e
Johannes Schaub - litb
2009-02-08 21:01:38