-->

C和C ++与外部的“C”键(C and C++ linkage with extern “C”)

2019-09-19 22:31发布

我在.h文件中定义的C ++函数,如下所示,并在cpp文件实现:

extern "C" void func(bool first, float min, float* state[6], float* err[6][6])
{
    //uses vectors and classes and other C++ constructs
}

我怎么能叫FUNC在C文件中? 如何设置我的文件架构/ makefile编译呢?

谢谢!

Answer 1:

要调用它在C,所有你需要做的是正常调用它。 因为你告诉编译器使用C调用约定和ABI与extern "C" ,就可以正常调用它:

func(args);

编译器,使用了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文件来代替。



Answer 2:

你叫由C以正常方式的功能。 但是,你需要用的extern "C"在预处理宏,以防止C编译器从看到它:

#ifndef __cplusplus
extern "C"
#endif
void func(bool first, float min, float* state[6], float* err[6][6]);

假设你正在与海湾合作委员会的工作,然后编译C代码gcc ,编译的C ++代码g++ ,然后用链接g++



Answer 3:

使用调用在C

func(... // put arguments here);

说的extern“C”你问的编译器不要裂伤你的名字。 否则,C ++编译器往往会损坏它们(即添加额外的符号,以使他们唯一的)链接之前。

你还需要确保你有设置为使用C调用约定。



Answer 4:

//header file included from both C and C++ files

#ifndef __cplusplus
#include <stdbool.h> // for C99 type bool
#endif

#ifdef __cplusplus
extern "C" {
#endif

void func(bool first, float min, float* state[6], float* err[6][6]);

#ifdef __cplusplus
} // extern "C"
#endif

// cpp file
#include "the_above_header.h"
#include <vector>

extern "C" void func(bool first, float min, float* state[6], float* err[6][6]);
{
    //uses vectors and classes and other C++ constructs
}

// c file
#include "the_above_header.h"

int main() {
    bool b;
    float f;
    float *s[6];
    float *err[6][6];
    func(b,f,s,err);
}


文章来源: C and C++ linkage with extern “C”