Calling a C Function from C Code
When integrating C and C code, it's common to encounter the need to call a C function from within C . While extern "C" can be used, this approach may fail due to compilation issues with g .
An alternative solution involves compiling the C code separately as a C module (.o file) using gcc:
gcc -c -o somecode.o somecode.c
Next, compile the C code separately:
g++ -c -o othercode.o othercode.cpp
Finally, link the two compiled objects together using the C linker:
g++ -o yourprogram somecode.o othercode.o
To enable the C compiler to recognize the C function declaration, include the header file in othercode.cpp, wrapped in extern "C":
extern "C" { #include "somecode.h" }
The header file somecode.h should contain a declaration for the C function:
#ifndef SOMECODE_H_ #define SOMECODE_H_ void foo(); #endif
The above is the detailed content of How Can I Successfully Call a C Function from C Code?. For more information, please follow other related articles on the PHP Chinese website!