使用 C 而不是 C++ 编译 header

Compiling header using C, instead of C++

我有一个 C++ 项目,我使用 Cmake 配置它以使用 Eclipse。我的问题是我添加了一个似乎无法编译的静态 C 库(即 svm-struct/svm-light),我猜它是作为 C++ 而不是 C 编译的。

我将库添加到我的项目中,如下所示:

SET(SVM_LIGHT_SRC_DIR "../../Libraries/svm_rank")
INCLUDE_DIRECTORIES(${SVM_LIGHT_SRC_DIR})

ADD_LIBRARY(
    svm_rank_lib STATIC
    ${SVM_LIGHT_SRC_DIR}/svm_light/svm_learn.c
    ${SVM_LIGHT_SRC_DIR}/svm_light/svm_common.c
    ${SVM_LIGHT_SRC_DIR}/svm_light/svm_hideo.c
    ${SVM_LIGHT_SRC_DIR}/svm_struct/svm_struct_learn.c
    ${SVM_LIGHT_SRC_DIR}/svm_struct/svm_struct_common.c
    ${SVM_LIGHT_SRC_DIR}/svm_struct/svm_struct_classify.c
    ${SVM_LIGHT_SRC_DIR}/svm_struct_api.c
    ${SVM_LIGHT_SRC_DIR}/svm_struct_learn_custom.c
)

add_executable(${PROJECT_NAME} ${SOURCES})
target_link_libraries(${PROJECT_NAME} svm_rank_lib)

Cmake 似乎配置得很好。在配置的输出中,它指定找到我的 C 和 C++ 编译器,并且它们 "work"。我使用 extern 将 header 添加到我的一个项目文件中,如下所示:

#ifdef __cplusplus
extern "C" {
# include "svm_struct/svm_struct_common.h"
}
#endif

当我去构建我的项目时,错误在这里:

../../Libraries/svm_rank/svm_struct/../svm_struct_api_types.h:75:11: error: expected member name or ';' after declaration specifiers
  double *class;    /* vector of scores that imply ranking */
  ~~~~~~  ^
1 error generated.

库 header 中有一个名为 "class" 的变量发生错误,我的猜测是它试图使用 C++ 而不是 C 来编译此库 header。首先,这是错误的原因吗?如果是这样,我应该如何解决这个问题?

double *class;    /* vector of scores that imply ranking */

class 如有帮助,请以蓝色突出显示。是一个保留字,意味着您不能将它用作变量或宏名称。尝试更改它,它应该会消除错误。

编辑

我误会你是用C编译的,但它似乎是用C++编译的。但我仍然支持我的回答,最好更改变量 class 以保持代码与 C++ 兼容,因为 class 是 C++ 中的保留字。

正如已经指出的那样,问题的根源是C库header声明了一个名为class的变量,这是C++中的关键字。

一旦 header 被 C++ 源文件引入,您就会遇到这个问题。请记住,header 不是自己编译的,而只是 copy-pasted 由预处理器编译到 #include 的源文件中。源文件的类型决定了 header 中的代码是被解释为 C 还是 C++。

您将 include 包装在 extern "C" 中这一事实并没有改变这一点。对于 header 中的声明,它只是 switches off C++-style name mangling,但代码仍然必须编译为有效的 C++。

这个问题最干净的解决方案是一种称为绝缘或编译器防火墙的技术。

您必须确保与有问题的库接触的所有部分都是 C-source 文件本身。代码的 C++ 部分仅通过该 C 部分的接口与库交互,但绝不会直接与库交互。特别是,您绝不能从任何 header 文件中 #include 库 header。

例如: my_interface.c

#include "svm_struct/svm_struct_common.h"  /* safe to include from a .c file */

struct opaque_ {
     /* you can use types from svm_struct_common in here */
};

opaque* initialize()
{
     /* you can create an opaque_ on the heap and
        manipulate it here, as well as give a
        pointer back to the C++ part */
}

void do_stuff(opaque*)
{
    /* do whatever you like with the stuff in opaque */
}

my_interface.h

/* no #includes in the header! */

/* the opaque type is only forward declared!
   C++ code can obtain a pointer to it,
   but cannot look inside */
struct opaque_;
typedef struct opaque_ opaque;

opaque* initialize();
void do_stuff(opaque*);

my_application.cpp

// we only include our own header, which we made sure is valid C++
extern "C" {
    #include <my_interface.h>
}

void do_stuff()
{
    opaque* context = initialize();
    do_stuff(context);
}