从 C++ 代码调用 C 函数 [英] Call a C function from C++ code
问题描述
我有一个 C 函数,我想从 C++ 调用它.我不能使用 "extern "C" void foo()
" 这种方法,因为 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 代码:
Compile the C code like this:
gcc -c -o somecode.o somecode.c
然后是这样的C++代码:
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 头文件即将到来.所以 othercode.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"
}
somecode.h
应该包含如下内容:
#ifndef SOMECODE_H_
#define SOMECODE_H_
void foo();
#endif
(我在这个例子中使用了 gcc,但任何编译器的原理都是一样的.分别作为 C 和 C++ 构建,然后将它们链接在一起.)
这篇关于从 C++ 代码调用 C 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!