Have not found the exact question i am asking in either google or here, everything talks about wanting to call c++ from c code or some part being compiled with c compiler and some other with c++ and then later linked together and the problems that arise from that which i do not want.
I want to compile and link C99 files with C++ compiler of Visual Studio in my all C++ application and be able to call the c functions without errors and problems.There will be no c linker involved or compiling some part with different compilers and linking together later, or any kind of trick. The headers are from C library (libcurl) and some others as i want to use them in my application. I do not want to use the C++ bindings i want to compile c code as c++. Can i trust c code be compiled as C++ code without major refactoring? What to do differently than when including C++ headers? What incompatibilities to expect?
In theory, C code should be able to be compiled as C++ code. At some point Dr.Stroustrup made the point that all code from ANSI C edition of the K&R compiles with a C++ compiler and has the same semantics as the code compiled with a C compiler has (this was construed that all ANSI C code would be valid C++ code which is, obviously, not the case, e.g., because many C++ keywords are not reserved identifiers in C).
However, certain idioms in C will require substantial changes to the C code if you want to compile the code with a C++ compiler. A typical example is the need to cast void* to the proper type in C++ which isn't needed in C and it seems it is frowned upon casting the result from malloc() to the proper pointer type although the effect is that it prevents the C code from being compiled with a C++ compiler (in my opinion a good think, e.g., because there the tighter rules may result in discovering problems in the C code even if the production version is being compiled with a C compiler). There are also a few subtle semantic differences as far as I know, although right now I can't easily pin-point one of them. That is, the same code compiled with a C and a C++ compiler may have defined but different results for both cases.
In practice, I doubt that you can simply compile a non-trivial body of C code with a C++ compiler and get a program which behaves the same as the original C code. If the C program you envision to compile with a C++ comes with a thorough set of test cases it may be feasible to port the code to C++ but it will involve more work than merely renaming the file from <name>.c to <name>.cpp. I could imagine that a tool could do the required conversions (a compiler compiling C source to C++ source) but I'm not aware of a such a tool. I'm only aware of the opposite direction yielding entirely unreadable code (for example Comeau C++ uses C as a form of portable assembler).
If you want to do this using visual studio, then it is not possible. MSVC doesn't support C99.
C and C++ are two different, but closely related, languages. C++ is nearly a superset of C++, but not quite (in particular, C++ has keywords that C lacks).
If your code depends on C99 features (i.e., features that are in C99 but not in C90), then you may be out of luck. Microsoft's C compiler does not support C99 (except for a few minor features; I think it permits // comments), and Microsoft has stated clearly that such support is not a priority. You may be able to modify the code so it's valid C90, depending on what features it uses.
Microsoft Visual Studio supports compiling both C and C++ (though it tends to emphasize C++). If you can get your C code compiling with the MS C compiler, I suggest doing just that rather than treating it as C++. C++ has features, particularly extern "C", that are specifically designed to let you interface C and C++ code. The C++ FAQ Lite discusses this in section 32.
If you really need to compile your C code as C++ for some reason, you can probably do so with a few minor source changes. Rename the source file from foo.c to foo.cpp, compile it, and fix any errors that are reported. The result probably won't be good C++, but you should be able to get it to work. There are a few constructs that are valid C and valid C++ with different semantics, but there aren't many of them, and you're not likely to run into them (but you should definitely keep that in mind).
If you want to continue maintaining the code as C++, my advice is to go ahead and make the changes needed to do that, and then stop thinking of it as C code.
The actual need to compile the same code both as C and as C++ is quite rare. (P.J. Plauger, for example, needs to do this, since he provides some libraries intended to be used in either language.) In most cases, C++'s extern "C" and other features are good enough to let you mix the two languages reasonably cleanly.
Related
I need to use pieces of a C library in a C++/CLI project. I forced the c files to compile as c++, the problem is that the library uses a lot of implicit enum to integer comparisons which c++ wont allow. Now I could just properly cast all of these but I'd like to achieve the result without modifying the original library code if possible (since the library is still being developed and I'd like to have plug n play capability). Is there a way to allow c++ to implicitly convert those enums?
The pedant answer is No.
The C++ Standard is stricter than the C Standard in that regard, and implicit casts from integer to enumerator or from void* to T* do not work out of the box.
You have a couple solutions ahead of you:
your compiler might have such a switch, it is not rare to have compiler switches to trigger non-Standard behaviors (often seen as "features"); I do not know of such switch but there are so many...
you could compile C code as C (possibly linking into a separate library if necessary)
you could edit the C code so it compiles as both C and C++
and finally, since it is a library in development, you could ask the authors to make sure their code compile as both C and C++
When reading this document, at the end of it, there is one sentence:
Historically, compilers for many languages, including C++ and Fortran, have been implemented as “preprocessors” which emit another high level language such as C.
Have no idea about preprocessors, any document? Does it mean all these languages will be translated into C source codes?
I think it would have been better to use the term source-to-source translator instead of "preprocessors" which makes it ambiguous in meaning , but it ain't any wrong to use it either.
Basically , A compiler is a computer program translates source code from a high-level programming language to a lower level language (e.g., assembly language or machine code).But the document in the question says :
Historically, compilers for many languages, including C++ and Fortran,
have been implemented as “preprocessors” which emit another high level
language such as C.
As per this description , it can be said that earlier , the compilers were implemented as source-to-source translator . A translator is also a form of preprocessor but its different from the preprocessor used in a program.
A translator is a computer program that translates a program written
in a given programming language into a functionally equivalent program
in a different language.
Now, coming to preprocessor used in a program , lets take an example :
#include <stdio.h>// a PREPROCESSOR directive
A preprocessor is a program that processes a source file before the
main compilation takes place,( similar to a translator ) but the difference lies in the fact that HERE it handles directives whose names begin with #.
Here #include is a directive. This directive causes the preprocessor to add the contents of the stdio.h file to your
program.This is a typical preprocessor action: adding or replacing text in the source code
before it’s compiled.
Some languages have been implemented by having the compiler generate C code which is then compiled by the C compiler. Notable examples include:
C++ in the earliest days (and C with Classes before that) — cfront generated C code from the C++ code. It ceased to be practical once C++ supported exceptions (read Stroustrup The Design and Evolution of C++ for more information), but not all C++ compilers used the technique (in fact, I don't know of any other compiler than cfront that did it).
Yacc is compiled to C code. Bison can be compiled to C or C++ code.
Lex is compiled to C code. Flex can be compiled to C or C++ code, I believe.
Informix ESQL/C converts Embedded SQL into pure C.
Informix 4GL converts I4GL source into ESQL/C, and then uses the ESQL/C compiler to create C code (and the C compiler to create object code and executables), so it has a multi-stage compiler (and I'm simplifying a bit).
The phrase "preprocessor" now has a totally different meaning, and is confusing to be used here. But, yes, here it means some compilers emits its source to another language.
It should be called source to source compiler. One of the examples is Cfront (designed by Bjarne Stroustrup himself), which converted C++ to C.
For the normal meaning of the phrase "preprocessor" in C++, see here.
No. Not necessarily. Many C++ compilers, LIKE THE GCC DOCUMENT SAID, (but not gcc/g++) produce C code output. Why do they do this? So they can piggyback on all the backend executable code that C compilers can compile to (X86, AMD, etc.) By having C as their destination code,they save alot of low end coding on the back end. Such compilers include the original Cfront and Comeau C/C++.
Note: I am using g++ version 4.3.4 to compile my C++ code.
So far, whenever I've wanted to use C style language elements in my code it seems that I can just include the C stuff mixed in and alongside my C++.
I know C++ is mostly backwards compatible with C... so I guess my questions are these:
What parts of C are not forwards compatible with C++?
Will professional programmers laugh at me if I continue to naively stick C stuff into my C++ code?
What is the proper way to have C and C++ code in the same .cpp file?
Can I continue to use g++ to compile my hybrid code?
For this question, I am mostly concerned with a solution that deals with a single .cpp file and a single g++ command to compile it. I don't really care about linking stuff at this point.
Picking out a couple of questions:
"What is the proper way to have C and C++ code in the same .cpp file?"
"Can I continue to use g++ to compile my hybrid code?"
If you want to mix C-style C++ in the same file as regular C++, just go ahead and do it. You can trust the compiler to pick up any issues - they will be minimal and not affect the structure. By the sound of it, you are not interested in getting C-linkage for its own sake, so even if the C-Code is in its own file, compile it as C++. As a matter of fact this is often done as a way of migrating from C to C++.
If you take this approach, your code is not truly hybrid C/C++. It is C++ with some of the code using C-style procedural idioms. C++ is fully intended to support this.
"Will professional programmers laugh at me if I continue to naively stick C stuff into my C++ code?"
It depends where you are using it and why. Well structured C code is good code. Sometimes C+ is much better than C at particular problems. Think hard before using C-style dynamic memory management. You will deserved to be laughed at if you use raw malloc()/free() and get it wrong.
I suggest that if you embark on this approach, you might later take the time to look back and consider whether or not you would have been better to use C++ idioms instread of procedural C.
A big gotcha with linking C and C++ code is that the C++ compiler needs to know that it is linking against functions that use the C calling conventions instead of the C++ calling conventions. To that end, you often have to wrap your C header files in something like this:
#ifdef __cplusplus
extern "C" {
#endif
... C function declarations here ...
#ifdef __cplusplus
}
#endif
For lots of details, see the C++ FAQ.
C++ is almost a superset of C. Therefore, pretty much any feature you can use in C is valid in C++ (but not the other way around).
People might laugh at you for coding some stuff like you would in C, but ignore them. I don't think it's naive, but that may make me naive. I can't tell.
There is no [real] way to seperate C and C++ code in the same file. It just goes with each other, because when you compile it as C++, it's not C any more. So "C alongside C++" is not really the way to think about it.
The only difference between thing in C that would keep code from compiling as C++ that I am aware of (besides C++ having more keywords) is the issue with void*s. In C, they will implicitly cast to any pointer type, but in C++, you have to have an explicit cast to cast them to another pointer type. There might be others, but I don't know them.
Oh, also, C++ doesn't support "default int". I don't know if it's still valid C these days, but if you leave off the type of a variable or the return type of a function, the compiler would just use int. C++ doesn't do that.
Most good C practices make for fine compiling C++. A couple of extra pointer casts and renamed identifiers will make for legal C++.
In style, however, C-style code is considered to be horrendous C++. The fact that you can write C-style code in C++ should be used if and only if you can't afford to write it in C++ to begin with- i.e., if it's legacy code.
Will professional programmers laugh at me if I continue to naively
stick C stuff into my C++ code?
Basically, yes. C-style coding is known in C++ as "horrendously unsafe", just to begin with. That kind of code is written only by people who don't genuinely know how to use C++. By that, I don't mean doing very low-level stuff like bit twiddling or binary re-interpretation, but things like pointer casting or manual resource management, and that will get you laughed at.
This is too broad a question; you should break it up into several. There's a way to link together C and C++ object files; C++ is backward compatible with C, and you can use C++ compiler to compile C code.
But, consider this code:
int main(void)
{
int class = 0;
int private = 1;
return private-class;
}
It's valid C code, and obviously won't compile on any C++ compiler if compiled as C++ code. Just an example.
Well, the obvious key difference is that C++ is object-oriented by design and C is not. That said, you shouldn't have any horrific show-stopping issues compiling C code with g++ unless you run into one of the nasty gotchas that are floating around. You can find a lot of good references for them, and I admit that my answer is far from exhaustive.
It's true that you cannot implicitly cast from void* in C++; it won't compile, whereas you'll see it fairly often in C.
You also have to explicitly declare functions in C++ before you use them, where you don't necessarily have to in C. (It's good form to do so, but not all C programmers do.)
http://www.cprogramming.com/tutorial/c-vs-c++.html Now that I'm out of things off the top of my head, this is a good little reference; I use it frequently.
I've seen a lot of arguments over the general performance of C code compiled with a C++ compiler -- I'm curious as to whether there are any solid experimental studies buried beneath all the anecdotal flame wars you find in web searches. I'm particularly interested in the GCC suite, but any data points would be interesting. (Comparing the assembly of "Hello, World!" is not as robust as I'd like. :-)
I'm generally assuming you use the "embedded style" flags -- no exceptions or RTTI. I also wouldn't mind knowing if there are studies on the compilation time itself. TIA!
Adding a datapoint (or at least an anecdote):
We were recently writing a math library for a small embedded-like target, and started writing it in C. About halfway through the project, we switched some of the files to C++, largely in order to use templates for some of the functions where we'd otherwise be writing many nearly-identical pieces of code (or else embedding 40-line functions in preprocessor macros).
At the point where we started switching over, we had a very careful look at the generated assembly code (using GCC) on a number of the functions, and confirmed that it was in fact essentially identical whether the file was compiled as C or C++ -- where by "essentially identical" I mean the differences were in things like symbol names and the stuff at the beginning and end of the assembly file; the actual instructions in the middle of the functions were exactly identical.
Sorry that I don't have a more solid answer.
Edit to add, 2013-03-24: Recently I came across an article where Rusty Russell compared performance on GCC compiled with a C compiler and compiled with a C++ compiler, in response to the recent switch to compiling GCC as C++: http://rusty.ozlabs.org/?p=330. The conclusions are interesting: The version compiled with a C++ compiler was very slightly slower; the difference was about 0.3%. However, that was entirely explained by load time differences caused by larger debug info; when he stripped the binaries and removed the debug info, the differences were less than 0.1% -- i.e., essentially indistinguishable from measurement noise.
I don't know of any studies off-hand, but given the C++ philosophy that you don't pay the price for features you don't use, I doubt there'd be any significant difference between compiling C code with the C compiler and with the C++ compiler.
I don't know of any studies and I doubt that anyone will spend the time to do them. Basically, when compiling with a C++ compiler, the code has the same semantic as when compiling with a C compiler, so it's down to optimization and code generation. But IMO these are much too much compiler-specifc in order to allow any general statements about C vs. C++.
What you mainly gain when you compile C code with a C++ compiler is a much stricter checking (function declarations etc.). IMO this would make compiling C code with a C++ compiler quite attractive. But note that, if you have a large C code base that's never run through a C++ compiler, you're likely facing a very steep up-hill battle until the code compiles clean enough to be able to see any meaningful warnings.
The GCC project is currently under a transition from C to C++ - that is, GCC may be implemented in C++ in the future, it is currently written in C. The next release of GCC will be written in the subset of C which is also valid C++.
Some performance tests were performed on g++ vs gcc, on GCC's codebase. They compared the "bootstrap" time, which means compiling gcc with the sysmem compiler, then compiling it with the resulting compiler, then repeating and checking the results are the same.
Summary: Using g++ was 20% slower. The compiler versions were slightly different, but it was thought that this wouldn't cause there 20% difference.
Note that this measures different programs, gcc vs g++, which although they mostly use the same code, have different front-ends.
I've not tried it from a performance standpoint, but I think compiling C applications with the C++ compiler is a good idea, as it will prevent you from doing "naughty" things such as using functions not declared.
However, the output won't be the same - at the very least, you'll get different symbols, which will render it (mostly) unlinkable with code from the C compiler.
So I think what you really mean is "Is it ok from a performance standpoint, to write C++ code which is very C-like and compile it with the C++ compiler" ?
You would also have to not be using some C99 things such as bool_t which C++ doesn't support on the grounds of having its own ones.
Don't do it if the code has not been designed for. The same valid language constructs can lead to different behavior if interpreted as C or as C++. You would potentially introduce very difficult to understand bugs. Less problematic but still a maintainability nightmare; some C constructs (especially from C99) are not valid in C++.
In the past I have done things like look at the size of the binary which for C++ was huge, that doesnt mean they simply linked in a bunch of unusued libraries. The easiest might be to use gcc -S myprog.cpp vs gcc -S myprog.c and diff the assembler output.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I have some C++ code. In the code there are many classes defined, their member functions, constructors, destructors for those classes, few template classes and lots of C++ stuff. Now I need to convert the source to plain C code.
I the have following questions:
Is there any tool to convert C++ code and header files to C code?
Will I have to do total rewrite of the code (I will have to remove the constructors,destructors and move that code into some init(), deinit() functions; change classes to structures, make existing member functions as function pointers in those newly defined structures and then invoke those functions using function pointers etc..)?
If I have to convert it manually myself, what C++ specific code-data constructs/semantics do I need to pay attention to while doing the conversion from C++ to C?
There is indeed such a tool, Comeau's C++ compiler. . It will generate C code which you can't manually maintain, but that's no problem. You'll maintain the C++ code, and just convert to C on the fly.
http://llvm.org/docs/FAQ.html#translatecxx
It handles some code, but will fail for more complex implementations as it hasn't been fully updated for some of the modern C++ conventions. So try compiling your code frequently until you get a feel for what's allowed.
Usage sytax from the command line is as follows for version 9.0.1:
clang -c CPPtoC.cpp -o CPPtoC.bc -emit-llvm
clang -march=c CPPtoC.bc -o CPPtoC.c
For older versions (unsure of transition version), use the following syntax:
llvm-g++ -c CPPtoC.cpp -o CPPtoC.bc -emit-llvm
llc -march=c CPPtoC.bc -o CPPtoC.c
Note that it creates a GNU flavor of C and not true ANSI C. You will want to test that this is useful for you before you invest too heavily in your code. For example, some embedded systems only accept ANSI C.
Also note that it generates functional but fairly unreadable code. I recommend commenting and maintain your C++ code and not worrying about the final C code.
EDIT : although official support of this functionality was removed, but users can still use this unofficial support from Julia language devs, to achieve mentioned above functionality.
While you can do OO in C (e.g. by adding a theType *this first parameter to methods, and manually handling something like vtables for polymorphism) this is never particularly satisfactory as a design, and will look ugly (even with some pre-processor hacks).
I would suggest at least looking at a re-design to compare how this would work out.
Overall a lot depends on the answer to the key question: if you have working C++ code, why do you want C instead?
Maybe good ol' cfront will do?
A compiler consists of two major blocks: the 'front end' and the 'back end'.
The front end of a compiler analyzes the source code and builds some form of a 'intermediary representation' of said source code which is much easier to analyze by a machine algorithm than is the source code (i.e. whereas the source code e.g. C++ is designed to help the human programmer to write code, the intermediary form is designed to help simplify the algorithm that analyzes said intermediary form easier).
The back end of a compiler takes the intermediary form and then converts it to a 'target language'.
Now, the target language for general-use compilers are assembler languages for various processors, but there's nothing to prohibit a compiler back end to produce code in some other language, for as long as said target language is (at least) as flexible as a general CPU assembler.
Now, as you can probably imagine, C is definitely as flexible as a CPU's assembler, such that a C++ to C compiler is really no problem to implement from a technical pov.
So you have: C++ ---frontEnd---> someIntermediaryForm ---backEnd---> C
You may want to check these guys out: http://www.edg.com/index.php?location=c_frontend
(the above link is just informative for what can be done, they license their front ends for tens of thousands of dollars)
PS
As far as i know, there is no such a C++ to C compiler by GNU, and this totally beats me (if i'm right about this). Because the C language is fairly small and it's internal mechanisms are fairly rudimentary, a C compiler requires something like one man-year work (i can tell you this first hand cause i wrote such a compiler myself may years ago, and it produces a [virtual] stack machine intermediary code), and being able to have a maintained, up-to-date C++ compiler while only having to write a C compiler once would be a great thing to have...
This is an old thread but apparently the C++ Faq has a section (Archived 2013 version) on this. This apparently will be updated if the author is contacted so this will probably be more up to date in the long run, but here is the current version:
Depends on what you mean. If you mean, Is it possible to convert C++ to readable and maintainable C-code? then sorry, the answer is No — C++ features don't directly map to C, plus the generated C code is not intended for humans to follow. If instead you mean, Are there compilers which convert C++ to C for the purpose of compiling onto a platform that yet doesn't have a C++ compiler? then you're in luck — keep reading.
A compiler which compiles C++ to C does full syntax and semantic checking on the program, and just happens to use C code as a way of generating object code. Such a compiler is not merely some kind of fancy macro processor. (And please don't email me claiming these are preprocessors — they are not — they are full compilers.) It is possible to implement all of the features of ISO Standard C++ by translation to C, and except for exception handling, it typically results in object code with efficiency comparable to that of the code generated by a conventional C++ compiler.
Here are some products that perform compilation to C:
Comeau Computing offers a compiler based on Edison Design Group's front end that outputs C code.
LLVM is a downloadable compiler that emits C code. See also here and here. Here is an example of C++ to C conversion via LLVM.
Cfront, the original implementation of C++, done by Bjarne Stroustrup and others at AT&T, generates C code. However it has two problems: it's been difficult to obtain a license since the mid 90s when it started going through a maze of ownership changes, and development ceased at that same time and so it doesn't get bug fixes and doesn't support any of the newer language features (e.g., exceptions, namespaces, RTTI, member templates).
Contrary to popular myth, as of this writing there is no version of g++ that translates C++ to C. Such a thing seems to be doable, but I am not aware that anyone has actually done it (yet).
Note that you typically need to specify the target platform's CPU, OS and C compiler so that the generated C code will be specifically targeted for this platform. This means: (a) you probably can't take the C code generated for platform X and compile it on platform Y; and (b) it'll be difficult to do the translation yourself — it'll probably be a lot cheaper/safer with one of these tools.
One more time: do not email me saying these are just preprocessors — they are not — they are compilers.