【问题标题】:Calling a function in a .cpp file from a .c file从 .c 文件调用 .cpp 文件中的函数
【发布时间】:2017-09-12 06:44:47
【问题描述】:

我一直在努力解决我正在从事的项目的问题。 假设我有几个文件:

reflection.h 
sll_insert.c
record_sll.c
io_recorder.cpp

上面提到的所有 cpp 和 c 文件都使用:

#include "reflection.h"

"reflection.h" 中有以下声明:

extern void io_recorder_fun_entry(char * name, TypedObject args[], int len);

extern void io_recorder_fun_exit(char * name, TypedObject args[], int len);

这两个函数在"io_recorder.cpp" 中实现,它们使用"io_recorder.cpp" 中的另一个函数io_record

现在,在"io_recorder.cpp",两个函数如下:

extern "C" void io_recorder_fun_entry(char * name, TypedObject args[], int len) {
    cout << "Entering function "<< name << endl; 
    io_record(args, len);
}

extern "C" void io_recorder_fun_exit(char * name, TypedObject args[], int len) {
    cout << "Exiting function "<< name << endl; 
    io_record(args, len);

}

当在io_record, there are calls being made to several functions declared in reflection.h and implemented in"record_sll.c"`时。

我有两个问题:

  1. 在这种情况下,C 和 C++ 之间的连接对我不起作用(我之前已经用其他文件尝试过它,它似乎以前也可以工作)。 尝试编译时,我收到如下错误:

    io_recorder.cpp: In function ‘void io_recorder_fun_entry(char*, TypedObject*, int)’:

    io_recorder.cpp:61:79: error: conflicting declaration of ‘void io_recorder_fun_entry(char*, TypedObject*, int)’ with ‘C’ linkage tern "C" void io_recorder_fun_entry(char * name, TypedObject args[], int len) {

    在来自io_recorder.cpp:4:0: reflection.h:32:13: note: previous declaration with ‘C++’ linkage extern void io_recorder_fun_entry(char * name, TypedObject args[], int len);的文件中

显然我做错了什么,我不知道是什么。 为了正确编译,我应该改变什么?

  1. 在之前的错误中,我使用io_record 时似乎无法识别来自record_sll 的函数。 它与问题1中的错误有什么关系吗?如果没有,我应该怎么做才能确保io_record 认识他们。

提前感谢您的帮助,我希望我能尽快解决这个问题。

【问题讨论】:

  • 您的标头声明中需要extern "C"
  • 我做了,但我得到了一个不同的错误。 reflect.h:32:8: 错误:字符串常量 extern "C" void io_recorder_fun_entry(char * name, TypedObject args[], int len) 之前的预期标识符或‘(’;
  • 这是一个可能有用的工作示例:stackoverflow.com/questions/31903005/…

标签: c++ include mixing


【解决方案1】:

从 C++ 的角度来看,您的定义相互矛盾:

  • 在您的标头中,您将这两个函数声明为普通的 c++ 函数(即没有特定的调用约定)
  • 在正文中,您将函数定义为使用 C 调用约定

这是一个问题,因为在所有使用您的标头的编译单元中,编译器将使用 c++ 调用序列生成代码,而不知道您的函数体使用另一个调用序列。因此出现错误消息。

要解决此问题,您必须将两种情况下的函数声明为extern "C"

从 C 的角度来看,但是,extern "C" 语法无法识别。因此,如果您想为 C++ 和 C 使用相同的标头,则需要一些额外的带有条件编译的gym:

#ifdef __cplusplus
extern "C" {  // this line will be compiled only if included in a .cpp file and not in a .c
#endif
    // your c function declaration go here without the extern "C"
#ifdef __cplusplus
}
#endif

您可以在this FAQ page 上找到有关混合 C 和 C++ 的更多信息。

【讨论】:

  • 谢谢,Galik 也说了同样的话。看看我写给他的评论,我现在得到一个不同的错误。
  • @baronzo1 是的,这是因为当头文件包含在 c 文件中时,c 语言无法识别这种 c++ 语法。 si 在 header 中你需要使用条件编译
  • @baronzo1 我已经编辑了答案以显示如何在两个 c 和 cpp 文件中使用相同的标题
  • 是的!我昨天这样做了,它解决了我的问题。 #ifdef 是我需要添加到 extern "c" 前缀的内容。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2013-03-27
  • 1970-01-01
  • 2021-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多