Home > Backend Development > C++ > body text

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

Barbara Streisand
Release: 2024-11-26 12:14:13
Original
120 people have browsed it

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
Copy after login

Next, compile the C code separately:

g++ -c -o othercode.o othercode.cpp
Copy after login

Finally, link the two compiled objects together using the C linker:

g++ -o yourprogram somecode.o othercode.o
Copy after login

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"
}
Copy after login

The header file somecode.h should contain a declaration for the C function:

#ifndef SOMECODE_H_
#define SOMECODE_H_

void foo();

#endif
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template