How to Invoke C Functions from C Code
Calling C functions from C can be challenging, particularly if the "extern "C" void foo()" approach fails in the g compilation environment. To address this issue, consider the following alternative:
Compilation and Linking
First, compile the C code using:
gcc -c -o somecode.o somecode.c
Next, compile the C code using:
g++ -c -o othercode.o othercode.cpp
Finally, link the two files together using the C linker:
g++ -o yourprogram somecode.o othercode.o
Header Declaration
In the C code, include the header where the C function is declared. However, to ensure the C compiler recognizes the header as a C header, use the following syntax:
extern "C" { #include "somecode.h" }
somecode.h
The somecode.h header should declare the C function, similar to the following:
#ifndef SOMECODE_H_ #define SOMECODE_H_ void foo(); #endif
Additional Notes
The above is the detailed content of How to Successfully Call C Functions from C Code?. For more information, please follow other related articles on the PHP Chinese website!