Compile GNU C project with C++ - c++

I just joined a project and there's a bunch of code (which has been written by 4 or 5 different people over the last 5 years). It's all C at this point, but I want to migrate the project to C++ in order to take advantage of OOP.
Step 1 will be to simply leave all the existing code in place and just selectively convert very small pieces of the functionality to be object oriented.
It's my understanding that C can be compiled by C++, but maybe I'm wrong about this.
So, before I invest a whole lot of time in trying to actually do it, am I likely to be able to get the existing C code to compile using C++ relatively easily?
Or, is this likely to involve a massive migration before it will work?
What factors affect the complexity of the task I'm proposing?
So to be clear - I'm not asking how big a project it will be to convert all of the code to objects, functions to methods, etc - but rather, just what I'm likely to face getting the existing C code to compile using the C++ compiler instead of the C compiler.
Thanks in advance - I look forward to any help/guidance you can provide.
EDIT
Sounds like it's really not a good idea. I always thought of c++ as an expansion of C, but it sounds like they're different enough that this is not an advisable path. Ultimately, I wasn't thinking of them as Different Languages, and was hoping that c++ was more backwards compatible with c than it sounds like it is. My initial searching made it look like people had done it to varying degrees of success, but the responses here make me think I should really just consider them to be two different languages. Thanks!

I always thought of c++ as an expansion of C, but it sounds like they're different enough that this is not an advisable path.
C++ is not an expansion of C. They are completely different languages. Compiling C code with C++ is not simply enabling "OO-mode". When you compile anything but trivial C code with a C++ compiler, you are potentially opening yourself up to a world of hurt due to the differences between the two languages.
am I likely to be able to get the existing C code to compile using C++ relatively easily?
Again, you have a fundamental misunderstanding -- C++ is not some extended version of C. They are different languages.
The best course of action is to slowly migrate your code to C++, but using two different compilers. Compile the C code with a C compiler, and compile the C++ code with a C++ compiler. It is not a challenging feat since any modern compiler suite (like GCC and clang) can compile both C and C++ very well.
is this likely to involve a massive migration before it will work?
If you intend to convert your code to C++, then yes.
One thing is worth mentioning: if you are compiling your C code with a C++ compiler, and calling it programming in C++, you're missing the spirit of the C++ development environment. If you're programming in C++, but using C code with very little OO, then what's the point of using C++? Just skip the overhead of OO and code in C. Using a C++ compiler is not some magic process that will instantly make your code better.

I think you should have a look here to get a list of (possible) issues.
What I did in the past for a C to C++ mgration was to leave the C code working as it should (C code compiled with a C compiler) and - in parallel - rewrite the code from scratch in C++.

Related

Using C++ API in C?

One day I decided to start writing a video game in plain old C.
It was a lot of fun, and three months later (I sometimes have little time away from the job) I found myself in the need of some physics engine.
I decided to use Bullet physics engine, because it seems like one of the better ones out there for what I need.
Then, I found out Bullet doesn't really have a C API but only a full C++ API. Its C API is not maintained.
After a day of cursing, I 'converted' my project into C++, which is a bold statement for saying I typecasted all heap allocation and I use new and delete instead of malloc and free, and wrapped up some definitions in 'extern "C" { ... }'.
Some people would probably shoot me for doing that, but I saw no other option to using a performance-tasking thing such as this physics engine, which only has a C++ API, in C.
So now, I'm compiling with g++, while still writing mostly "C" code.
I find myself a little less happy, because the code no longer feels as pure.
C++ gives me some strange error messages, while I have nothing against the language I often do not like the g++ parser.
Aside from the fact that I can now happily bounce objects into each other, some of the smallness and purity of my pet project has been deserted now.
I'm wondering if I did the right thing. Can I ask for some advice, should I just carry on and not worry about using a C++ compiler for my 'mostly' C code? Are there other ways to use this API in C without any performance hits or overdone maintenance work?
I'm wondering if I did the right
thing.
Well, you needed a component for your project, and instead of inventing it again from scratch, you reused an existing piece of software. It actually sounds right to me.
Can I ask for some advice, should I
just carry on and not worry about
using a C++ compiler for my 'mostly' C
code?
You don't need to worry at all. C++ is almost 100% C compatible. There are no penalties on doing that. You have actually earned better compile-time checkings due to a much stricter type system.
Are there other ways to use this API
in C without any performance hits or
overdone maintenance work?
No, you can't use the API in C without converting your code to C++. C++ identifiers are mangled: this means that, even if you were ready to use the C++ API from plain C, you wouldn't know how to refer to them. Theoretically this is possible, in practice it isn't.
Your way is the correct one.
Good luck with that game!
I think you're overly concerning yourself with things that aren't really problems. You say that some of the purity has gone. Well, I can understand this. You wrote it in C and then, realizing you had to use C++ to use an API of choice, shoehorned it in. Now it doesn't feel like your pet baby anymore. This is a subconscious issue, not a programming one.
I suggest you bite the bullet (haha), and rewrite your project in C++. Then it will be pure again, you'll learn a lot on the way, and won't feel like your C-child is being sodomized.
Depending on how tightly coupled the different subsystems of your engine are, it might be feasible to write different parts of the engine in different languages.
For example, you could factor out the physics part into a C++ module which exports a C API and let the rest of your application stay in C. However, it might make more sense to write the central part of the system in C++ and refactor your existing C code into seperate modules.
If you want to write your project in C, write it in C and make a C wrapper for the library; have a look at this question for some advice about it.
Otherwise, rewrite your project in C++; but please, don't write yet another C project with some C++ here and there, in my experience these projects can quickly become a mess (and if you write code with a C mindset but calling C++ code weird things start to happen when exceptions are added to the mix).
Don't worry about writing mostly C code and compiling it with C++. Just adopt using new/delete instead of malloc/free and you'll be fine. The advantage of using new is that you don't have to cast the result to the proper pointer type (implicit casts from void* to other pointers are disallowed in C++) and that new will never return an invalid pointer. You loose realloc() though. (And no, don't even think of mixing new/delete with realloc :))
The only reasons you would keep a project as "pure C" are either because of source code compatibility, tool support, or because of language standards (MISRA-C etc). "I want it to feel pure" is probably not a very rational argument.
If keeping the code as pure C for such reasons is important, your could have written a "wrapper" DLL (assuming Windows) in C++, which does all the communication with your 3rd party API. You'd get a fair bit of overhead of course.
The strange error messages are no doubt caused by the stricter typing in C++, which can be a bless or a curse depending on the situation. A C++ compiler will be more likely to slap your fingers when encountering dangerous implicit typecasts (integer promotions etc) and it will likely enforce stricter "const correctness". But at the same time, it will moan about void pointers, which are considered good generic programming in C, but dangerous, sloppy and possibly redundant in C++.
One option is to convert the C++ code to C using LLVM. See this FAQ from the project's website: Can I convert C++ code to C code?

Is C++ built on top of C?

Does C++ code gets converted to C before compilation ?
A few C++ compilers (the original cfront, Comeau C++) use C as an intermediate language during compilation. Most C++ compilers use other intermediate langauges (e.g. llvm).
Edit: Since there seems to be some misunderstanding about the history: "C with classes" started out using a preprocessor called "Cpre". At that time, it was seen strictly as a dialect of C, not a separate language in itself. In December 1983, people were starting to view it as a separate language, and the name C++ was invented. As it happens, development of cfront started in April 1983, so a reasonably usable version became available (to a select few) just about the same time as the name "C++" came into use. This appears to be mostly coincidence though.
As far as producing C as its output, that was really quite common on Unix. Just for example, the Berkeley Pascal compiler and at least a couple of Fortran compilers also produced C as their output.
There is, however, a huge difference between Cpre and Cfront. Although both produced C as their output, Cpre did virtually no syntax checking of its own -- it looked for a few specific things, and did a relatively mechanical translation on them. It wasn't until the C compiler looked at the result that real syntactical analysis was done. If your code contained a syntax error, it was almost certain that it wouldn't be caught until the C compiler parsed the output from Cpre.
Cfront, however, did full syntactical analysis of the source code itself, so (short of a bug in its code generator) you'd never see a syntax error from the C compiler. The C compiler was simply used as a code generator so nobody needed to rewrite CFront to accommodate different processors, object file formats, etc.
If you want to get into more detail, chapter 2 of The Design and Evolution of C++ is devoted almost entirely to the "C with Classes" time frame (and there are various other details about it spread throughout the book).
No, but like most myths there's a shred of truth to this. The original compiler for C with classes (which later became C++) was nicknamed CFront and did translate to C.
Not in most modern compilers.
The original C++ compiler was actually a preprocessor however. It generated C code, which was then compiled by a C compiler.
In the early days of C++ compilers, some did it that way. I haven't seen a C++ compiler implemented that way since the late 1980s however.
As others have answered. NO.
However if you want to use an OOP language like C#, and have your code compiled into C I recommend you take a look at Vala.
the title seems to ask is C++ a superset of C, i.e. can you just dump any c code in a c++ compiler and it will work? In which case, yes it is, sort of...
one major difference is that C automatically casts pointers for you, c++ does not, you need to cast the manually...
any one remember anything else?
thats all I remember from the horrible process of converting a massive C project to compile under c++ for some reason...

Why are many VMs written in C when they look like they have C++ features?

I noticed some not so old VM languages like Lua, NekoVM, and Potion written in C.
It looked like they were reimplementing many C++ features.
Is there a benefit to writing them in C rather than C++?
I know something about Lua.
Lua is written in pure ANSI Standard C and compiles on any ANSI platform with no errors and no warnings. Thus Lua runs on almost any platform in the world, including things like Canon PowerShot cameras. It's a lot harder to get C++ to run on weird little embedded platforms.
Lua is a high-performance VM, and because C cannot express method calls (which might be virtual or might not) and operator overloading, it is much easier to predict the performance of C code just by looking at the code. C++, especially with the template library, makes it a little too easy to burn resources without being aware of it. (A full implementation of Lua including not only VM but libraries fits in 145K of x86 object code. The whole language fits even in a tiny 256K cache, which you find at L2 on Intel i7 and L1 on older chips. Unless you really know what you're doing, it's much harder to write C++ that compiles to something this small.)
These are two good reasons to write a VM in C.
It looked like they were reimplementing many C++ features.
Are you suggesting it's easier to implement polymorphism in C++ rather than C? I think you are greatly mistaken.
If you write a VM in C++, you wouldn't implement polymorphism in terms of C++'s polymorphism. You'd roll your own virtual table which maps function names to pointers, or something like that.
People are used to C. I have to admit that I'm more likely to write C for my own projects, even though I've been writing C++ since cfront 1.0.
If you want complete control over things, C is a little easier.
One obvious answer is interoperability. Any time language X has to call functions defined in language Y, you usually make sure that either X or Y is C (the language C, that is)
C++ doesn't define an ABI, so calling C++ code from another language is a bit tricky to do portably. But calling C code is almost trivial. That means that at least part of your VM is probably going to have to be written in C, and then why not be consistent and write the entire thing in C?
Another advantage of C is that it's simple. Everyone can read it, and there are plenty of programmers to help you write it. C++ is, for good and bad, much more of an experts language. You can do a lot of impressive things in C++, and it can save you a lot of work, but there are also fewer programmers who are really good at it.
It's much harder to be "good" at C++, and until one is good at it they will have a lot of bugs and problems. Now, especially when working on large projects with many people, the chance that one of them won't be good enough is much bigger, so coding the project in C is often less risky. There are also portability issues - C code is much easier to port across compilers than C++.
Lua also has many features that are very easy to implement in Lisp, so why doesn't it take that as a basis? The point is that C is little more than glorified assembler code with only a thin layer of abstraction. It is like a somewhat polished blank slate, on which you can build your higher level abstractions. C++ is such a building. Lua is a different building, and if it had to use C++ abstractions, it would have to bend its intent around the existing C++ structure. Starting from the blank slate instead gives you the freedom to build it like you want.
In many cases, code in C could be much faster than C++. For instance most of the functions in the stdio.c library are faster than iostream. scanf is faster than cin, printf is faster than cout etc.
and VMs demand high performance, so C code makes perfect sense, although the programs would most probably take longer to develop.
C++ is implemented in C. I suspect everyone was following the C++ approach.
Even though modern C++ compilers skip (or conceal) the explicit C++ to C translation as a discrete step, the C++ language has peculiarities that stem from the underlying C implementation.
Two examples.
Pointers in addition to references is entirely because of C. References are sufficient, and that's the way Java, Python and Ruby all work.
The classes are not first-class objects that exist at run-time because the class is only a way to define the attributes and method functions in the underlying C code. Class objects exist at run-time in Java, Python and Ruby, and can be manipulated.
Just a side note, you should look into CLR (Rotor-incarnation) and Java sources and you will note it is far more C++-as-C rather than modern or good C++. So it has a parallel there and it is a side-effect of abstracting for toys and making it average-performance happy for the crowd in managed languages.
It also helps avoid pitfalls of naive C++ usage. Exceptions and all other sort of things (bits David at boost consulting kicked off and more while we build sequencers and audio sampling before he even had a job :) are an issue too..
Python integration is another matter, and has a messy history in boost for example.. But for primitive data types and interfaces/interop and machine abstraction, well it is quite clear nothing beats C. No compiler issues either, and it still bootstraps many things before you get to anything as influential as it is/was/will be.
Stepanov recognised this achievement when he nailed STL, and Bjarne nailed it with templates.. Those are the three things always worth thinking about, as you don't have a decent incarnation of them in popular managed languages, not to that expressivness and power. All of that more than 20 years later, which is remarkable and all still bootstrap via C/C++.. Legacy of goodness (but I'm not defending 'dark age' C code c1982-2000, just the idea, yuo can misuse anything ).

Should "portable" C compile as C++?

I got a comment to an answer I posted on a C question, where the commenter suggested the code should be written to compile with a C++ compiler, since the original question mentioned the code should be "portable".
Is this a common interpretation of "portable C"? As I said in a further comment to that answer, it's totally surprising to me, I consider portability to mean something completely different, and see very little benefit in writing C code that is also legal C++.
The current C++ (1998) standard incorporates the C (1989) standard. Some fine print regarding type safety put aside, that means "good" C89 should compile fine in a C++ compiler.
The problem is that the current C standard is that of 1999 (C99) - which is not yet officially part of the C++ standard (AFAIK)(*). That means that many of the "nicer" features of C99 (long long int, stdint.h, ...), while supported by many C++ compilers, are not strictly compliant.
"Portable" C means something else entirely, and has little to do with official ISO/ANSI standards. It means that your code does not make assumptions on the host environment. (The size of int, endianess, non-standard functions or errno numbers, stuff like that.)
From a coding style guide I once wrote for a cross-platform project:
Cross-Platform DNA (Do Not Assume)
There are no native datatypes. The only datatypes you might use are those declared in the standard library.
char, short, int and long are of different size each, just like float, double, and long double.
int is not 32 bits.
char is neither signed nor unsigned.
char cannot hold a number, only characters.
Casting a short type into a longer one (int -> long) breaks alignment rules of the CPU.
int and int* are of different size.
int* and long* are of different size (as are pointers to any other datatype).
You do remember the native datatypes do not even exist?
'a' - 'A' does not yield the same result as 'z' - 'Z'.
'Z' - 'A' does not yield the same result as 'z' - 'a', and is not equal to 25.
You cannot do anything with a NULL pointer except test its value; dereferencing it will crash the system.
Arithmetics involving both signed and unsigned types do not work.
Alignment rules for datatypes change randomly.
Internal layout of datatypes changes randomly.
Specific behaviour of over- and underflows changes randomly.
Function-call ABIs change randomly.
Operands are evaluated in random order.
Only the compiler can work around this randomness. The randomness will change with the next release of the CPU / OS / compiler.
For pointers, == and != only work for pointers to the exact same datatype.
<, > work only for pointers into the same array. They work only for char's explicitly declared unsigned.
You still remember the native datatypes do not exist?
size_t (the type of the return value of sizeof) can not be cast into any other datatype.
ptrdiff_t (the type of the return value of substracting one pointer from the other) can not be cast into any other datatype.
wchar_t (the type of a "wide" character, the exact nature of which is implementation-defined) can not be cast into any other datatype.
Any ..._t datatype cannot be cast into any other datatype
(*): This was true at the time of writing. Things have changed a bit with C++11, but the gist of my answer holds true.
No. My response Why artificially limit your code to C? has some examples of standards-compliant C99 not compiling as C++; earlier C had fewer differences, but C++ has stronger typing and different treatment of the (void) function argument list.
As to whether there is benefit to making C 'portable' to C++ - the particular project which was referenced in that answer was a virtual machine for a traits based language, so doesn't fit the C++ object model, and has a lot of cases where you are pulling void* of the interpreter's stack and then converting to structs representing the layout of built-in object types. To make the code 'portable' to C++ it would have add a lot of casts, which do nothing for type safety.
Portability means writing your code so that it compiles and has the same behaviour using different compilers and/or different platforms (i.e. relying on behaviour mandated by the ISO standard(s) wherever possible).
Getting it to compile using a different language's compiler is a nice-to-have (perhaps) but I don't think that's what is meant by portability. Since C++ and C are now diverging more and more, this will be harder to achieve.
On the other hand, when writing C code I would still avoid using "class" as an identifier for example.
No, "portable" doesn't mean "compiles on a C++ compiler", it means "compiles on any Standard comformant C compiler" with consistent, defined behavior.
And don't deprive yourself of, say, C99 improvements just to maintain C++ compatibility.
But as long as maintaining compatibility doesn't tie your hands, if you can avoid using "class" and "virtual" and the the like, all the better. If you're writing open source, someone may want to port your code to C++; if you're wring for hire, you company/client may want to port sometime in the future. hey, maybe you'll even want to port it to C++ in the future
Being a "good steward" not leaving rubbish around the campfire, is just good karma in whatever you do.
And please, do try to keep incompatibilities out of your headers. Even if your code is never ported, people may need to link to it from C++, so having a header that doesn't use any C++ reserved words, is cool.
It depends. If you're doing something that might be useful to a C++ user, then it might be a good idea. If you're doing something that C++ users would never need but that C users might find convenient, don't bother making it C++ compliant.
If you're writing a program that does something a lot of people do, you might consider making it as widely-usable as possible. If you're writing an addition to the Linux kernel, you can throw C++ compatability out the window - it'll never be needed.
Try to guess who might use your code, and if you think a lot of C++ fans might find your code useful, consider making it C++ friendly. However, if you don't think most C++ programmers would need it (i.e. it's a feature that is already fairly standardized in C++), don't bother.
It is definitely common practice to compile C code using a C++ compiler in order to do stricter type checking. Though there are C-specific tools to do that like lint, it is more convenient to use a C++ compiler.
Using a C++ compiler to compile C code means that you commonly have to surround your includes with extern "C" blocks to tell the compiler not to mangle function names. However this is not legal C syntax. Effectively you are using C++ syntax and your code which is supposedly C, is actually C++. Also a tendency to use "C++ convenience" starts to creep in like using unnamed unions.
If you need to keep your code strictly C, you need to be careful.
FWIW, once a project gains a certain size and momentum, it is not unlikely that it may actually benefit from C++ compatibility: even if it not going to be ported to C++ directly, there are really many modern tools related to working/processing C++ source code.
In this sense, a lack of compatibility with C++, may actually mean that you may have to come up with your own tools to do specific things. I fully understand the reasoning behind favoring C over C++ for some platforms, environments and projects, but still C++ compatibility generally simplifies project design in the long run, and most importantly: it provides options.
Besides, there are many C projects that eventually become so large that they may actually benefit from C++'s capabilities like for example improved suport for abstraction and encapsulation using classes with access modifiers.
Look at the linux (kernel) or gcc projects for example, both of which are basically "C only", still there are regularly discussions in both developer communities about the potential gains of switching to C++.
And in fact, there's currently an ongoing gcc effort (in the FSF tree!) to port the gcc sources into valid C++ syntax (see: gcc-in-cxx for details), so that a C++ compiler can be used to compile the source code.
This was basically initiated by a long term gcc hacker: Ian Lance Taylor.
Initially, this is only meant to provide for better error checking, as well as improved compatibility (i.e. once this step is completed, it means that you don't necessarily have to have a C compiler to to compile gcc, you could also just use a C++ compiler, if you happen to be 'just' a C++ developer, and that's what you got anyway).
But eventually, this branch is meant to encourage migration towards C++ as the implementation language of gcc, which is a really revolutionary step - a paradigm shift which is being critically perceived by those FSF folks.
On the other hand, it's obvious how severely gcc is already limited by its internal structure, and that anything that at least helps improve this situation, should be applauded: getting started contributing to the gcc project is unnecessarily complicated and tedious, mostly due to the complex internal structure, that's already to started to emulate many of the more high level features in C++ using macros and gcc specific extensions.
Preparing the gcc code base for an eventual switch to C++ is the most logical thing to do (no matter when it's actually done, though!), and it is actually required in order to remain competitive, interesting and plain simply relevant, this applies in particular due to very promising efforts such as llvm, which do not bring all this cruft, complexity with them.
While writing very complex software in C is often course possible, it is made unnecessarily complicated to do so, many projects have plain simply outgrown C a long time ago. This doesn't mean that C isn't relevant anymore, quite the opposite. But given a certain code base and complexity, C simply isn't necessarily the ideal tool for the job.
In fact, you could even argue that C++ isn't necessarily the ideal language for certain projects, but as long as a language natively supports encapsulation and provides means to enforce these abstractions, people can work around these limitations.
Only because it is obviously possible to write very complex software in very low level languages, doesn't mean that we should necessarily do so, or that it really is effective in the first place.
I am talking here about complex software with hundreds of thousands lines of code, with a lifespan of several decades. In such a scenario, options are increasingly important.
No, matter of taste.
I hate to cast void pointers, clutters the code for not much benefit.
char * p = (char *)malloc(100);
vs
char * p = malloc(100);
and when I write an "object oriented" C library module, I really like using the 'this' as my object pointer and as it is a C++ keyword it would not compile in C++ (it's intentional as these kind of modules are pointless in C++ given that they do exist as such in stl and libraries).
Why do you see little benefit? It's pretty easy to do and who knows how you will want to use the code in future.
No, being compilable by C++ is not a common interpretation of portable. Dealing with really old code, K&R style declarations are highly portable but can't be compiled under C++.
As already pointed out, you may wish to use C99 enhancements. However, I'd suggest you consider all your target users and ensure they can make use of the enhancements. Don't just use variable length arrays etc. because you have the freedom to but only if really justified.
Yes it is a good thing to maintain C++ compatibility as much as possible - other people may have a good reason for needing to compile C code as C++. For instance, if they want to include it in an MFC application they would have to build plain C in a separate DLL or library rather than just being able to include your code in a single project.
There's also the argument that running a compiler in C++ mode may pick up subtle bugs, depending on the compiler, if it applies different optimisations.
AFAIK all of the code in classic text The C programming language, Second edition can be compiled using a standard C++ compilers like GCC (g++). If your C code is upto the standards followed in that classic text, then good enough & you're ready to compile your C code using a C++ compiler.
Take the instance of linux kernel source code which is mostly written in C with some inline assembler code, it's a nightmare compiling the linux kernel code with a C++ compiler, because of least possible reason that 'new' is being used as an variable name in linux kernel code, where as C++ doesn't allow the usage of 'new' as a variable name. I am just giving one example here. Remember that linux kernel is portable & compiles & runs very well in intel, ppc, sparc etc architectures. This is just to illustrate that portability does have different meanings in software world. If you want to compile C code using a C++ compiler, you are migrating your code base from C to C++. I see it as two different programming languages for most obvious reason that C programmers doesn't like C++ much. But I like both of them & I use both of them a lot. Your C code is portable, but you should make sure you follow standard techniques to have your C++ code portable while you migrate your C code to C++ code. Read on to see from where you'd get the standard techniques.
You have to be very careful porting the C code to C++ code & the next question that I'd ask is, why would you bother to do that if some piece of C code is portable & running well without any issues? I can't accept managebility, again linux kernel a big code source in C is being managed very well.
Always see the two programming languages C & C++ as different programming languages, though C++ does support C & its basic notion is to always support for that wonderful language for backward compatibility. If you're not looking at these two languages as different tools, then you fall under the land of popular, ugly C/C++ programming language wars & make yourself dirty.
Use the following rules when choosing portability:
a) Does your code (C or C++) need to be compiled on different architectures possibly using native C/C++ compilers?
b) Do a study of C/C++ compilers on the different architectures that you wish to run your program & plan for code porting. Invest good time on this.
c) As far as possible try to provide a clean layer of separation between C code & C++ code. If your C code is portable, you just need to write C++ wrappers around that portable C code again using portable C++ coding techniques.
Turn to some good C++ books on how to write portable C++ code. I personally recommend The C++ programming language by Bjarne Stroustrup himself, Effective C++ series from Scott meyers & popular DDJ articles out there in www.ddj.com.
PS: Linux kernel example in my post is just to illustrate that portability does mean different meanings in software programming & doesn't criticize that linux kernel is written in C & not in C++.

Isn't saying "C/C++" wrong? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I've seen a lot of questions around that use improperly the expression "C/C++".
The reasons in my opinion are:
Newbie C and C++ programmers probably don't understand the difference between the two languages.
People don't really care about it since they want a generic, quick and "dirty" answer
While C/C++ could sometimes be interpreted as "either C or C++", I think it's a big error. C and C++ offer different approaches to programming, and even if C code can be easily implemented into C++ programs I think that referring to two separate languages with that single expression ( C/C++ ) is wrong.
It's true that some questions can be considered either as C or C++ ones, anyway.
What do you think about it?
C/C++ is a holdout from the early days of C++, where they were much more similar than they were today. It's something that wasn't really wrong at first, but is getting more-so all the time.
The basic structure is similar enough that most simple questions do still work between the two, though. There is an entire Wikipedia article on this topic: http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B
The biggest fallacy that comes from this is that because someone is well-versed in C, they will be equally good at C++.
Please remember that the original implementations of C++ were simply as a pre-compiler that output C code for the 'real' compiler. All C++ concepts can be manually coded (but not compiler-enforced) in plain C.
"C/C++" is also valid when referring to compilers and other language/programming tools. Virtually every C++ compiler available will compile either - and are thus referred to as "C/C++" compilers. Most have options on whether to treat .C and .CPP files based on the extension, or compile all of them as C or all of them as C++.
Also note that mixing C and C++ source in a single compiler project was possible from the very first C/C++ compiler. This is probably the key factor in blurring the line between the languages.
Many language/programming tools that are created for C++ also work on C because the language syntax is virtually identical. Many language tools have separate Java, C#, Python versions - but they have a single "C/C++" version that works for C and C++ due to the strong similarities.
We in our company have noticed the following curious fact: if a job applicant writes in his CV about "advanced C/C++ knowledge", there is usually a good chance that he really knows neither ;)
The two languages are distinct, but they have a lot in common. A lot of C code would compile just fine on a C++ compiler. At the early-student level, a lot of C++ code would still work on a C compiler.
Note that in some circumstances the meaning of the code may differ in very subtle ways between the two compilers, but I suppose that's true in some circumstances even between different brands of C++ compiler if you're foolish enough to rely on undefined or contested/non-conformant behavior.
Yes and no.
C and C++ share a lot in common (in fact, the majority of C is a subset of C++).
But C is more oriented "imperating programming", whereas C++, in addition to C paradigm, has more paradigms easily accessible, like functional programing, generic programing, object oriented programing, metaprograming.
So I see the "C/C++" item saying either as "the intersection of C and C++" or "familiarity with C programing as well as C++ programing", depending on the context.
Now, the two languages are really different, and have different solutions to similar problems. A C developer would find it difficult to "parse/understand" a C++ source, whereas a C++ developer would not easily recognize the patterns used in a C source.
Thus, if you want to see how far the C is from the C++ in the "C/C++" expression, a good comparison would be the GTK+ C tutorials, and the same in C++ (GTKmm):
C : GTK+ Hello World: http://library.gnome.org/devel/gtk-tutorial/stable/c39.html#SEC-HELLOWORLD
C++ : GTKmm Hello World: http://www.gtkmm.org/docs/gtkmm-2.4/docs/tutorial/html/sec-helloworld.html
Reading those sources is quite enlightening, as they are, as far as I parsed them, producing exactly the same thing, the "same" way (as far as the languages are concerned).
Thus, I guess the C/C++ "expression" can quite be expressed by the comparison of those sources.
:-)
The conclusion of all this is that it is Ok if used on the following contexts:
describing the intersection of C and C++
describing familiarity with C programing as well as C++ programing
describing compatible code
But it would not be for:
justifying keeping to code in a subset of C++ (or C) for candy compatibility with C (or C++) when compatibility is not desired (and in most C++ project, it is not desired because quite limitating).
asserting that C and C++ can/should be coded the same way (as NOT shown by the GTK+/GTKmm example above)
I think it's more of the second answer - they want something that's easily integrated into their project.
While a C answer may not be idiomatic C++ (and vice versa), I think that's one of C++'s big selling points - you can basically embed C into it. If an idiomatic answer is important, they can always specify C/C++/C++ with STL/C++ with boost/etc.
An answer in lisp is going to be pretty unusable. But an answer in either C or C++ will be directly usable.
Yeah, C/C++ is pretty useless. It seems to be a term mostly used by C++ newbies. We C-only curmudgeons just say "C" and the experienced C++ folks know how much it has diverged from C and so they properly say "C++".
Even if C is (nearly) a subset of C++, this doesn't really have any bearing on their actual usage. Practically every interesting C feature is frowned upon in modern C++ code:
C pointers (use iterators/smart pointers/references instead), macros (use templates and inline functions instead), stdio (use iostreams instead), etc. etc.
So, as Alex Jenter put it, it's unlikely that anyone who knows either language well would say C/C++. Saying that you know how to program in "C/C++" is like saying you know how to program in "Perl/PHP"... sure they've got some significant similarities, but the differences in how they are actually used are vast.
C/C++ often means a programiing style, which is like C and classes, or C and STL :-) Technicaly it is C++, but minimum of its advantages are used.
I agree. I read the C tag RSS feed, and I see tons of C++ questions come through that really don't have anything to do with C.
I also see this exchange a lot:
Asker: How do you do this in C?
Answer: Use the X library for C++.
Asker: OK, how about someone actually answer my question in C?
I use that term myself, and it is because it is my style, I don't use boost, stl or some other things, not even standard C++ libs, like "cout" and "cin", I program C but using classes, templates and other (non-library) features to my advantage.
I can say that I am not a master of C, neither a master of C++, but I am really good at that particular style that I use since 10 years ago. (and I am still improving!)
I was under the impression that all c code is valid c++ code.
Isn’t saying “C/C++” wrong?
No, it isn't. Watcom International Corporation for example, founded more than 25 years ago, called their set of C and C++ compilers and tools "Watcom C/C++", and this product is still developed and available in the open-source form as OpenWatcom C/C++
If it is a complex question needing to write more than one function, yes, it can be wrong.
If it is just to ask a detail about sprintf or bit manipulation, I think it can be legitimate (the latter can even be tagged C/C++/Java/C#, I suppose...).
Whoever is asking the question should write C, C++ or C/C++ depending on the question.
From what I've seen, you can write C++ code the C way or the C++ way. Both work, but C++ code that is not written C style is usually easier to maintain in the long run.
In the end, it all depends on the particular question. If someone is asking how to concatenate strings, than it is very important whether he wants C or C++ solution. Or, another example, if someone is asking for a qsort algorithm. To support different types, you might want to use macros with C and templates with C++, etc.
This was too long for a comment, so I had to make it an answer, but it's in response to Jeff B's answer.
Please remember that the original
implementations of C++ were simply as
a pre-compiler that output C code for
the 'real' compiler.
I have a friend (who writes C++ compilers -- yes, plural), who would take offense to your first sentence. A compiler whose object code is C source code is every bit as much a compiler as any other. The essence of a compiler is that it understands that syntax of the language, and generates new code based on that. A pre-processor has no knowledge of the language and merely reformats its input.
Remember that the C Compilers which would compile the output of those C++ compilers, would themselves output ASM code would would then be run through an assembler.
I tend to put C / C++ in my questions.
Typically I am looking for something that I can use in my c++ application.
If the code is in C or in C++ then I can use it, so I would rather not just limit the possible answers to one or the other.
Not only these two languages are different, but also the approaches are different. C++ is an OO language, while C is procedural language.
Do I have to mention templates?
Also, there are differences in C and C++ standards. If something is good in C, doesn't have to compile in C++