How to use C code in C++

int *pi;
pi = malloc( 25 * sizeof( int ) );
error: invalid conversion from 'void*' to 'int*' [-fpermissive]
pi = malloc( 25 * sizeof( int ) );
^
Need for EDU purposes
1
2
3
int *pi = (int*)malloc(25 * sizeof(int));
...
free (pi);


But you shouldn't use malloc/free in C++ - instead use new/delete
https://en.cppreference.com/w/cpp/language/new
https://en.cppreference.com/w/cpp/language/delete

1
2
3
auto pi {new int[25]{}};
...
delete [] pi;

> How to use C code in C++
You use a C compiler to compile your C code.

How you use your C compiler depends on what compiler you have.

Most compiler drivers take a clue from the filename extension, so one thing might be just to name your source files to end with .c rather than .cpp or .c++

Or you can force the language on the command line.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<stdio.h>
int main()
{
#ifdef __cplusplus
    printf("Compiled with C++, char constant size=%zd\n", sizeof('a'));
#else
    printf("Compiled with C, char constant size=%zd\n", sizeof('a'));
#endif
    return 0;
}

$ gcc foo.c
$ ./a.out 
Compiled with C, char constant size=4
$ gcc -xc++ foo.c
$ ./a.out 
Compiled with C++, char constant size=1

Yes, you can get different answers out of valid code depending on whether you choose to compile your code as C or C++.

Just casting malloc to make the compiler STFU is not the way out of whatever problem you're looking at.

You can mix C and C++ code, but the relevant parts of the C code need to be compiled with the C compiler part of your toolchain.
Then read this.
https://isocpp.org/wiki/faq/mixing-c-and-cpp
Ideally avoid dynamic memory as much as possible in C++.

if you need realloc or other similar things in c++ for a very low level tool, then using the C functions with casting is OK in c++ instead of new/delete. But you must be very careful when handing the void pointers from C's memory functions.
A good C++ compiler will consume C code without too much problem, recommended to use the C++ headers instead of the C headers. <cstdlib> instead of <stdlib.h> for example.

The machine code generated by a C++ compiler will be similar, not the same, from the code generated by a true C compiler. If that matters.

Current C++ compilers such as MSVC or GCC/MinGW will happily munch on (most) C code.

The C stdlib was inherited into the C++ stdlib when C++ was created. It isn't the current C stdlib version, C17 with C23 on the way. There are a few C stdlib features that are not part of the C++ stdlib because of that. What those features are you should investigate for yourself.

https://en.cppreference.com/w/
Topic archived. No new replies allowed.