Home >Backend Development >C++ >How to Successfully Call a C Function from C Code?
Calling a C function from C can present challenges, especially if the "extern "C" void foo()" approach fails due to compilation issues with g . To address this, a different strategy is proposed:
Compilation:
Compile the C code:
gcc -c -o somecode.o somecode.c
Compile the C code:
g++ -c -o othercode.o othercode.cpp
Linking:
Link the compiled files together using the C linker:
g++ -o yourprogram somecode.o othercode.o
Header Inclusion:
To inform the C compiler that a C header is included, update the othercode.cpp file with the following:
extern "C" { #include "somecode.h" }
somecode.h Header File:
Create a header file (somecode.h) to declare the C function:
#ifndef SOMECODE_H_ #define SOMECODE_H_ void foo(); #endif
Note:
This method separates compilation into C and C stages, followed by linking. The choice of compiler (gcc in this example) is flexible, but the principle remains the same.
The above is the detailed content of How to Successfully Call a C Function from C Code?. For more information, please follow other related articles on the PHP Chinese website!