To integrate a C function into C code, one might consider utilizing the standard idiom "extern "C" void foo()". However, this approach may fail during compilation with g , despite successful compilation with gcc.
To address this issue, adhere to the following steps:
Compile the C code using:
gcc -c -o somecode.o somecode.c
Compile the C code using:
g++ -c -o othercode.o othercode.cpp
Combine the compiled objects using the C linker:
g++ -o yourprogram somecode.o othercode.o
Include a declaration for the C function in the C code, preceded by "extern "C" {}:
extern "C" { #include "somecode.h" }
Define the C function in the header file somecode.h:
#ifndef SOMECODE_H_ #define SOMECODE_H_ void foo(); #endif
Note: The commands in this example were for gcc. The fundamental approach remains applicable to any compiler. Compile the code separately for C and C , then link them.
The above is the detailed content of How Can I Successfully Call C Functions from Within C Code?. For more information, please follow other related articles on the PHP Chinese website!