简体   繁体   English

使用C和C ++文件进行项目

[英]Project with both c and c++ files

Can I have a project that has some parts written in c and other parts written in c++ ? 我能否有一个包含用c编写的某些部分和用c ++编写的其他部分的项目? Is this possible ? 这可能吗 ?

Yes. 是。

If you have control of the C code, then inside your C header files you should have: 如果您可以控制C代码,则在C头文件中应具有:

#ifdef __cplusplus
extern "C" {
#endif

// normal header stuff here

#ifdef __cplusplus
};
#endif

That way they can be properly interpreted when included by both C and CPP code files. 这样,当C和CPP代码文件都包含它们时,就可以正确地解释它们。

If you include C code in your C++ via a header, and it doesn't include the code above, and you don't have enough control of it to make the necessary modifications, be sure to use eg 如果您通过标头将C代码包含在C ++中,并且其中不包含上述代码,并且您没有足够的控制权进行必要的修改,请确保使用例如

extern "C" {
#include "some_c_header.h"
};

Note that you can use this as a modifier for declarations too, eg: 请注意,您也可以将其用作声明的修饰符,例如:

extern "C" void someFunction();

Note that C++ has this mechanism for importing C functionality. 请注意,C ++具有导入C功能的这种机制。 C doesn't have one for importing C++, and trying to include C++ code in a C compilation unit will pretty quickly end in a bunch of error messages. C没有用于导入C ++的代码,而试图在C编译单元中包含C ++代码将很快导致一堆错误消息。 One consequence of this is that your main function will need to be C++. 这样的结果之一是您的主要功能将必须是C ++。

You need a compiler that can compile both languages (I have not heard of a C++ compiler that cannot do that), or compile them with a fitting compiler each and link them (in which case the answer of @sje397 applies). 您需要一个可以同时编译两种语言的编译器(我从未听说过C ++编译器无法做到),或者需要使用合适的编译器来编译它们并链接它们(在这种情况下,@ sje397的答案适用)。 There is a good explanation on the subject in the C++ FAQ Lite . C ++ FAQ Lite中对此主题有很好的解释。

Yes it is very much possible. 是的,这很有可能。 In fact usually legacy systems refactored later on usually have legacy code which is C as the core but with C++ wrappers on top of it. 实际上,通常在以后重构的旧系统中通常都以C为核心,但在其之上具有C ++包装器。

Yes you can. 是的你可以。 C++ is mainly a superset of C. There might be some exceptions, but for the most part it is quite normal to include stuff written in C in your C++ projects. C ++主要是C的超集。可能会有一些例外,但是在大多数情况下,在C ++项目中包含用C编写的内容是很正常的。

是的,您可以拥有一个同时包含C和C ++代码的项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM