Make g++ compile C using gcc rules
Solution 1
Put them in separate files and declare the functions in the file with the C++. You don't need to create a header.
C++ code (blah.cpp):
// C function declarations
extern "C" {
int foo(int x);
int bar(int x);
}
// C++ function definitions
int qux(int x) {
return foo(bar(x));
}
C code (blah.c):
// C function definitions
int foo(int x) {
return x * 3;
}
int bar(int x) {
return x * 2;
}
Solution 2
That's a neat idea, but I don't think g++ makes any provisions for this. Perhaps you can just use g++ flags that make it a bit more permissive about what it accepts, while simultaneously fixing up the C code somewhat, until they meet in the middle.
Solution 3
Make 2 copies of the same source, one to be compiled by g++, the other gcc. Block off the C++ parts with
#ifdef __cplusplus
#if 0
...
#endif
#endif
so that gcc doesn't try to compile the C++ code.
Add the extern "C" {} to the g++ block so it knows about the function prototypes for the C part. You don't need a header to do this; it can be written in the source file.
Compile them separately and link them.
jmatias
Updated on June 04, 2022Comments
-
jmatias almost 2 years
I have a .cpp source file that contains both C and C++ code. The C code does not compile using g++ so I need to use gcc.
Using
extern "C" {}
does not work because that's just to tell the compiler how to handle the function names, I want g++ to behave like gcc entirely for one portion of the code, and like g++ for another.I know I could just put them on separate files, but then I would have to create a header for the file with the C code to be able to use it in the other C++ file and that is what I'm trying to avoid. I don't want those functions visible to anyone other than that C++ code.
Does that make sense? Is this even possible? Thanks!
-
jmatias over 12 yearsYep, that works. That is what I'm doing right now, actually. There are a lot of functions & struct declarations though - I was trying to avoid copy pasting all that. I was wondering if there was a magic thing like a #pragma or something.
-
jmatias over 12 yearsWouldn't that cause the code to never be compiled? The code is between the
#if 0
&#endif
.