为什么extern"C"组C++类(不是标题)在这里?

foo*_*foo 15 c++ linkage

我正在搜索SVM库并遇到BudgetedSVM.

在源代码中,我发现了一个不寻常的用法,就像这样:

#sample.h

#ifndef SAMPLE_H
#define SAMPLE_H

//no header included or namespace declared here

#ifdef __cplusplus
extern "C" {
#endif

//no header included or namespace declared too

class Sample: public Parent
{
public:
    Sample();
    ~Sample();

    type0 fun(type1 val1, type2 val2);
    ...
};

#ifdef __cplusplus
}
#endif

#endif // SAMPLE_H
Run Code Online (Sandbox Code Playgroud)

如图所示,标头中不需要额外的头或命名空间,这些都在cpp文件中.

这是我的想法:

  1. 为什么extern "C"(通常用于C接口)将C++类分组?这种用法对某些东西有用吗?

  2. 即使type0,type1并type2出现了,自己的头在这里没有包括在内,但在cpp文件(如sample.h).当我调用类的Sample,但是,我必须包括这些报头(例如type0.h,type1.h,type2.h),这似乎很不方便.

Ros*_*ost 19

根据C++标准 C语言在确定类成员名称和类成员函数的函数类型的语言链接时忽略了语言链接.

所以这样的分组看起来毫无意义的,除非type0,type1或者type2是内联定义函数指针,在这种情况下,他们将有C链接.

在情况下type0,type1或者type2是用户定义的类型及其定义被放置在单独的页眉它违反了良好的C/C++风格的规则-所有的标题应是独立的,不需要额外的夹杂物进行编译.

回答主要问题('为什么?') - 看起来C语言链接只是从另一个标题中盲目地复制粘贴(可能是纯C,它有意义).或者它可能是故意做的 - 由于"一致性"的原因.