CompuServe Thread

#Using C from C++

3 messages in this thread
#7191From: Burt JohnsonJul 20, 1993 2:11 AM
I am new to C++, so this may be a dumb questions, but what the heck… I have some C functions that I have used for eons to handle tasks I need frequently. I am now getting into my first TCL program, and figured I'd just bring along my standard "support.c" file. Everything compiled fine. However, when I placed a call to a function in that file, my link said that the function was undefined. I solved the problem simply by changing the name of the file from "support.c" to "support.cp" and typecasting a few places where C++ says that it can't implicitely convert from (void *) to (char *). My questions are: 1) Why does changing the file to *.cp fix the problem? I know that this makes it use the C++ compiler instead of the C compiler, but why does that make any difference to the linker here? 2) Why can't C++ convert from (void *) to (char *) without typecasting? I thought that void matched any type, or is that no longer true in C++? Is there another way to indicate "a pointer of any type"? – Burt
#7324From: Joe SewellJul 21, 1993 5:13 PM
The reason changing the extension from .c to .cp made it work is the functions are now C++ functions, complete with mangled names. That's where you were running into trouble before. To inhibit the name mangling, put 'extern "C"' in front of the prototype, like so: extern "C" void *myFunc (int arg1, float arg2); // or extern "C" { void *myFunc (int arg1, float arg2); int *myFunc1 (int arg1, float arg2); // also a C function } Now, for the pointer conversion. Let me see if I understand what you're saying. You want to do something like this in C++? void *vPtr; char *cPtr; // assume pointers are initialized & what-not cPtr = vPtr; // or equivalent in a function call In other words, you want to put the contents of a void pointer into a char pointer? C++ lets you assign any pointer type to variable of type void *, but NOT the other way around; C++ considers such things "unsafe." Typecasting, however, works, as in (char *)vptr = cPtr; Joe
#7339From: Burt JohnsonJul 21, 1993 9:23 PM
>> C++ lets you assign any pointer type to variable of type void *, but NOT the other way around; C++ considers such things "unsafe." Typecasting, however, works Yes, I knew that typecasting worked, and was what I did to make that code work. I was just surprised that going _both_ ways is OK in C but not in C++ and wanted to verify that I was understanding what I saw. Thanks for verifying that I wasn't _too_ far off the deep end. 🙂 – Burt