在C中调用文件C ++函数 [英] Calling C++ functions from C file
问题描述
我很新的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 ++联动和调用约定。 (实际上这是最重要的功能就是名称重整 - 由C ++编译器会改变一个符号的名称进程。这样就可以有在参数类型各不相同的同名函数)的externC
(在你的头文件present)是围绕它自己的方式 - 它规定,这是一个C函数,从C code,如调用。未进行重整。
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.
您有的externC
在你的头文件,这是一个良好的开端,但你的C ++文件没有包括它并没有为externC
在声明中,所以它不知道编译它作为一个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.
这篇关于在C中调用文件C ++函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!