用C项目中使用C ++文件 [英] Using C++ files in C project

查看:101
本文介绍了用C项目中使用C ++文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是出于好奇:有没有使用C ++文件用C项目的方法吗?随着文件我的意思是,从头文件和库访问功能,并利用它们在自己的项目为已经解决问题的能力。

Just out of curiosity: Is there a way to use C++ files in C projects? With files I mean the ability to access functions from header files and libraries and use them in your own projects for problems that have already been solved.

推荐答案

如果您外部化的函数,变量和结构与

If you externalize your functions, variables and struct with

extern "C" {
    int global;
}

在报头文件,并用

extern "C" int global = 20; 

在C ++ code,这将是从C- code使用。该规则同样适用于功能。

in your C++ code, it will be usable from C-code. The same rule applies to functions.

您可以打电话,甚至有适当的原型方法。例如:

You can even call methods with appropriate prototypes. E.g:

class C 
{
public: 
     c(int);
     int get();
};

在C-包装在你的.cpp可能看起来像:

The C-Wrapper in your .cpp could look like:

extern "C" void * createC(int i)
{
     return (void *) new C(i);
}

extern "C" int Cget(void *o)
{ 
     return ((C *)o)->get();
}

这篇关于用C项目中使用C ++文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆