Home >Backend Development >C++ >How Can I Successfully Call a C Function from C Code?

How Can I Successfully Call a C Function from C Code?

Barbara Streisand
Barbara StreisandOriginal
2024-11-26 12:14:13195browse

How Can I Successfully Call a C Function from C   Code?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn