Reputation: 91
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!
Upvotes: 2
Views: 13587
Reputation: 207
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.
Upvotes: 1
Reputation: 81694
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.
Upvotes: 2
Reputation: 234474
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;
}
Upvotes: 5