从C文件调用C++函数

use*_*375 11 c c++ merge call

我是C和C++的新手.但我有一些C++函数,我需要从C调用它们.我做了一个我需要做的例子


main.c:

#include "example.h"      
#include <stdio.h>

int main(){   
    helloWorld();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

example.h:

 #ifndef HEADER_FILE
 #define HEADER_FILE

 #ifdef __cplusplus
     extern "C" {
 #endif
         void helloWorld();
 #ifdef __cplusplus
     }
 #endif

 #endif
Run Code Online (Sandbox Code Playgroud)

example.cpp:

#include <iostream.h>

void helloWorld(){
    printf("hello from CPP");
} 
Run Code Online (Sandbox Code Playgroud)

它只是不起作用.我仍然收到未定义参考错误_helloWorld在我main.c.这个问题在哪里?

asv*_*kau 14

简短回答:

example.cpp应包括example.h.

更长的回答:

在C++中声明函数时,它具有C++链接和调用约定.(实际上,最重要的特性是名称修改 - C++编译器改变符号名称的过程,以便您可以使用在参数类型中有相同名称的函数.) extern "C"(存在于头文件中)是你的方式 - 它指定这是一个C函数,可以从C代码调用,例如.没有被破坏.

你有extern "C"头文件,这是一个很好的开始,但你的C++文件不包括它并且extern "C"在声明中没有,所以它不知道将它编译为C函数.