How do I mix C and C++ in a Qt Creator Project
-
I know how to mix C and C++ using makefiles. But I can't seem to find a description of how to do this in the documentation. I am running Linux Mint 17.1.
I am doing a project mainly in C++. But I have to make calls to an existing C library (libtiff). Of course, I know how to declare the extern "C" functions in my C++.
But I also have to write some of my own C routines e.g. to supply error handlers and other callbacks that will interface to the C library.
So can I add a C file to my C++ project? Qt Creator does not seem to give me that option.
-
Hi,
You don't need to write specific C files to use a library that has a C interface. Just use it in your C++ code.
-
@SGaist The trouble is that the existing C library will be calling back to functions that I provide - and I suppose these must be C functions, because as I understand it the C library will have no idea how to call back to a C++ function, what with potential name mangling etc.
That is, the sequence will be (a) my C++ calling (b) an existing C function which will call (c) my C callback function.
So, if that is correct, I need to add a C callback function to my C++ project.
Or can I just declare a function in a C++ file to be extern C in Qt Creator?
-
A C callback is nothing more than a function outside of a class so you can just write it in the implementation file where you need to use it.
-
That is a very useful link.
In any case, I just did what you suggested earlier and it seems to work. I actually just plunked my callback at the top of the file containing my C++ main and all seems to be well.
I will do some reading to make sure I understand what is going on fully, but for now it works.
Thank you very much for your helpful and quick response. I can now proceed!
-
@jakep said:
So I should expect g++ (or any C++ compiler) to compile a C++ function outside of a class in a way that is ABI compatible with C?
No, not really. C++ allows overloading and the symbol names are decorated by the C++ compiler, which is not the case in C code. Your problem is linkage related and doesn't actually have to do with QtCreator or OS. When you want to call C functions from C++ you declare them with C linkage (the
extern "C"
construct). The other way around is also true. To have C call a C++ compiled function you'd need to declare the function to have C linkage (the same way). Callbacks work for you, because you're passing a pointer to function and you don't really care about the ABI or how the symbols are resolved. You could pass a class method (by casting it appropriately) as a callback and it might even work because you're doing that in runtime and it doesn't need to be resolved by the linker. If you want to expose your objects/functions from C++ to be available to a C code at link-time, you'll need to declare them with C-linkage.Kind regards.