具有外部"C"的C和C ++链接 [英] C and C++ linkage with extern "C"
问题描述
我在.h文件中定义了如下的C ++函数,并在.cpp文件中实现:
I have a C++ function defined in a .h file as follows and implemented in a .cpp file:
extern "C" void func(bool first, float min, float* state[6], float* err[6][6])
{
//uses vectors and classes and other C++ constructs
}
如何在C文件中调用func?如何设置我的文件体系结构/makefile来对此进行编译?
How can I call func in a C file? How do I set up my file architecture / makefile to compile this?
谢谢!
推荐答案
要在C中调用它,您所需要做的就是正常调用它.因为您告诉编译器在extern "C"
中使用C调用约定和ABI,所以可以正常调用它:
To call it in C, all you need to do is call it normally. Because you told the compiler to use the C calling conventions and ABI with extern "C"
, you can call it normally:
func(args);
要编译,请将其用于C ++:
To compiler, use this for the C++:
g++ -c -o myfunc.o myfunc.cpp
然后针对C:
gcc -c -o main.o somec.c
比链接:
g++ -o main main.o myfunc.o
确保该函数的C ++标头使用仅C构造.因此,请将<vector>
之类的内容包含在.cpp
文件中.
Make sure that the C++ header for the function uses ONLY C CONSTRUCTS. So include things like <vector>
in the .cpp
file instead.
这篇关于具有外部"C"的C和C ++链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!