简体   繁体   中英

Will using extern C keyword for a specific header in C++ allow for conversion from void* to char*?

I am using an open source hydrodynamics code written in C. They have a lot of functions for reading and writing Input/Output parallely. I am writing a program to do post analysis of outputs in C++, and I want to use these functions in my code by including their header file. Problems such as printf etc are taken care of when I include the header file (ah) within

extern "C" {
#include "a.h"
}.

But when I try to compile it an error shows up saying

/Src/Parallel/al_io.c:234:5: error: invalid conversion from 'void*' to 'char*' [-fpermissive] a = (void *)va;

Which means it is not allowing this in spite of the extern keyword. Is this normal? If so is there another way to allow these functions to work. Editing each of them by hand is not possible as there are about thousands of them. Thanks!!

Is this normal?

Yes. extern "C" changes the linkage. The program is still compiled as a C++ program.

In the implementation of a extern "C" function, you have access to all the features of C++. The flip side of it is that it is compiled just like a regular C++ function. All the syntactic constraints of a C++ program apply to such a function.

If so is there another way to allow these functions to work.

You can use static_cast<char*>(...) .

 /Src/Parallel/al_io.c:234:5: error: invalid conversion from 'void*' to 'char*' [-fpermissive] a = (void *)va; 

You need to compile this third-party C library as C, not as C++.

As you have discovered, wrapping the third-party library's headers in extern "C" does not do that. (You do still need to do this, or the program as a whole will fail to link, but it doesn't fix your immediate problem.)

What does do that is using the correct "compiler driver" to compile each source file. You didn't tell us which compiler you're using, or anything at all about how you are building the program, so I can't be terribly specific about that, but: make sure you are using a program named something like "cc", "gcc", or "clang" to compile all files named whatever.c , not a program named something like "c++", "g++", "clang++". Compilers with "++" in their name should only be used to compile source files that actually contain C++ code.

When it comes time to link all the .o files together into a complete program, you will either need to use the compiler with "++" in its name to do that, or you will need to name the C++ runtime library explicitly on the command line (eg gcc foo.o bar.o baz.o -lstdc++ ). The name of the C++ runtime library can vary and can be difficult to discover, so I recommend the former approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM