我是 C 和 C++ 的新手。但是我有一些 C++ 函数,我需要从 C 中调用它们。我举了一个例子来说明我需要做什么
main.c:
#include "example.h"
#include <stdio.h>
int main(){
helloWorld();
return 0;
}
example.h:
#ifndef HEADER_FILE
#define HEADER_FILE
#ifdef __cplusplus
extern "C" {
#endif
void helloWorld();
#ifdef __cplusplus
}
#endif
#endif
example.cpp:
#include <iostream.h>
void helloWorld(){
printf("hello from CPP");
}
它只是行不通。我的 main.c
中仍然收到对 _helloWorld
undefined reference 的错误。问题出在哪里?
最佳答案
简答:
example.cpp
应该包含 example.h
。
更长的答案:
当您在 C++ 中声明一个函数时,它具有 C++ 链接和调用约定。 (在实践中,最重要的特征是 name mangling - C++ 编译器更改符号名称的过程,以便您可以拥有具有相同名称但参数类型不同的函数。) extern "C “
(存在于您的头文件中)是您解决它的方式 - 它指定这是一个 C 函数,可从 C 代码调用,例如。没有损坏。
您的头文件中有 extern "C"
,这是一个好的开始,但您的 C++ 文件不包含它并且没有 extern "C"
在声明中,所以它不知道将其编译为 C 函数。
关于c++ - 从 C 文件调用 C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12615683/