Coder25
Coder25

Reputation: 311

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++ ? Is this possible ?

Upvotes: 6

Views: 1358

Answers (6)

T.T.T.
T.T.T.

Reputation: 34573

How to mix C and C++:
http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html

Upvotes: 2

sje397
sje397

Reputation: 41852

Yes.

If you have control of the C code, then inside your C header files you should have:

#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.

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 e.g.

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

Note that you can use this as a modifier for declarations too, e.g.:

extern "C" void someFunction();

Note that C++ has this mechanism for importing C functionality. 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. One consequence of this is that your main function will need to be C++.

Upvotes: 9

Björn Pollex
Björn Pollex

Reputation: 76848

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). There is a good explanation on the subject in the C++ FAQ Lite.

Upvotes: 2

Brian Campbell
Brian Campbell

Reputation: 333046

Yes, you can have a project with both C and C++ code.

Upvotes: 1

Daren Thomas
Daren Thomas

Reputation: 70344

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.

Upvotes: 1

Alok Save
Alok Save

Reputation: 206566

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.

Upvotes: 1

Related Questions