Warm tip: This article is reproduced from serverfault.com, please click

how to make g++ ignore calloc pointer type error when compiling c code

发布于 2020-12-03 08:53:35

For example, the line below compiles ok with gcc,

float *m = calloc(rows*cols, sizeof(float));

but g++ complains about the pointer type mismatch like below.

../../../../../YOLO/darknet/src/gemm.c:33:22: error: invalid conversion from ‘void*’ to ‘float*

(maybe callc always returns void* in c++?)
Can I make g++ just ignore this pointer type mismatch error? (I found this link but they say it's unavoidable. If we can use c code from inside c++ code without fixing this everywhere, it would be nice.)

Questioner
Chan Kim
Viewed
1
user1502256 2020-12-03 17:11:32

The solution to this problem is actually not to add a static_cast as eerorika suggests but compiling the C code with a C compiler. There are a number of subtle differences between C and C++ that can lead to unexpected results, and the compiler won't catch them all. So even if you change all the type warnings you might still end up with broken code.

To ensure that you can call the C code from C++ you should mark the code as extern "C" inside the C headers like so:

#ifdef __cplusplus
extern "C" {
#endif

[your definitions]

#ifdef __cplusplus
}
#endif