从C + + code调用C函数 [英] Call a C function from C++ code
问题描述
我有一个C函数,我想从C ++调用。我不能使用的externC无效美孚()
之类的方法,因为C函数没有使用G ++编译。但用gcc编译罚款。任何想法如何从C ++调用该函数?
I have a C function that I would like to call from C++. I couldn't use "extern "C" void foo()
" kind of approach because the C function failed to be compiled using g++. But it compiles fine using gcc. Any ideas how to call the function from C++?
推荐答案
编译C code是这样的:
Compile the C code like this:
gcc -c -o somecode.o somecode.c
然后,C ++ code是这样的:
Then the C++ code like this:
g++ -c -o othercode.o othercode.cpp
然后将它们链接在一起,用C ++链接:
Then link them together, with the C++ linker:
g++ -o yourprogram somecode.o othercode.o
您也必须告诉C ++编译器C头即将到来,当你包括C函数的声明。因此,其它code.cpp
开始:
You also have to tell the C++ compiler a C header is coming when you include the declaration for the C function. So othercode.cpp
begins with:
extern "C" {
#include "somecode.h"
}
约code.h
应该包含这样的:
#ifndef SOMECODE_H_
#define SOMECODE_H_
void foo();
#endif
(Ⅰ在本实施例中使用的gcc,但原理是任何编译器是相同的。作为C和C分别生成++分别接链接在一起的。)的
这篇关于从C + + code调用C函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!