从 C 文件调用 C++ 函数

2021-12-27 00:00:00 merge c call c++

我对 C 和 C++ 很陌生.但是我有一些 C++ 函数,我需要从 C 中调用它们.我举了一个例子来说明我需要做什么

I am quite new to C and C++. But I have some C++ functions which I need to call them from C. I made an example of what I need to do

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 的未定义引用的错误.问题出在哪里?


It just doesn't work. I still receive the error of undefined reference to _helloWorld in my main.c. Where is the the problem?

推荐答案

简答:

example.cpp 应该包括 example.h.

更长的答案:

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

When you declare a function in C++, it has C++ linkage and calling conventions. (In practice the most important feature of this is name mangling - the process by which a C++ compiler alters the name of a symbol so that you can have functions with the same name that vary in parameter types.) extern "C" (present in your header file) is your way around it - it specifies that this is a C function, callable from C code, eg. not mangled.

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

You have extern "C" in your header file, which is a good start, but your C++ file is not including it and does not have extern "C" in the declaration, so it doesn't know to compile it as a C function.

相关文章