I have a C function that I would like to call from C++. I couldn't use "extern "C" void foo()
" kind of approach because the C function failed to be compiled using g++. But it compiles fine using gcc. Any ideas how to call the function from C++?
No you can't have a nested function in C . The closest you can come is to declare a function inside the definition of another function. The definition of that function has to appear outside of any other function body, though.
The main function always acts as a driver function and calls other functions. We can also write function call as a parameter to function. In the below code, first add(num1, num2) is evaluated, let the result of this be r1. The add(r1, num3) is evaluated.
In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function. The C programming language supports recursion, i.e., a function to call itself.
Compile the C code like this:
gcc -c -o somecode.o somecode.c
Then the C++ code like this:
g++ -c -o othercode.o othercode.cpp
Then link them together, with the C++ linker:
g++ -o yourprogram somecode.o othercode.o
You also have to tell the C++ compiler a C header is coming when you include the declaration for the C function. So othercode.cpp
begins with:
extern "C" { #include "somecode.h" }
somecode.h
should contain something like:
#ifndef SOMECODE_H_ #define SOMECODE_H_ void foo(); #endif
Let me gather the bits and pieces from the other answers and comments, to give you an example with cleanly separated C and C++ code:
foo.h:
#ifndef FOO_H #define FOO_H void foo(void); #endif
foo.c
#include "foo.h" void foo(void) { /* ... */ }
Compile this with gcc -c -o foo.o foo.c
.
bar.cpp
extern "C" { #include "foo.h" //a C header, so wrap it in extern "C" } void bar() { foo(); }
Compile this with g++ -c -o bar.o bar.cpp
And then link it all together:
g++ -o myfoobar foo.o bar.o
Rationale: The C code should be plain C code, no #ifdef
s for "maybe someday I'll call this from another language". If some C++ programmer calls your C functions, it's their problem how to do that, not yours. And if you are the C++ programmer, then the C header might not be yours and you should not change it, so the handling of unmangled function names (i.e. the extern "C"
) belongs in your C++ code.
You might, of course, write yourself a convenience C++ header that does nothing except wrapping the C header into an extern "C"
declaration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With