I recently took over a project written in C and C++ that will be compiled using the MS Visual Studio 2003 compiler. Since I have a little lack on experience with compiler settings and compiler output I want to know if the given setup realy makes a difference (according to compilation output or performance).
The project uses a mixture of C and C++. The main part is written in C but uses some classes written in C++.
So the first part of the question is: does the (MS VS 2003) compiler makes a difference per file (compiling plain c for .cpp files using only c functionality and compiling c++ style for files using the classes)?
Could there be a reason for using that (performance boost, backward compatibility)?
The project also does not use try-catch blocks (since it is not plain C). But the exception handling options in the compiler settings are not disabled.
So the second part of the question: could there be still a performance boost (or any other logical reason) for not using try-catch but NOT disabling it in the compiler?
Yes, I am quite confused by this setup and trying to understand.
Fairly hard to decode, I'll give it a shot. The default behavior is to get the C compiler when the source code filename extension ends in .c and the C++ compiler when it ends in .cpp. There is no greater scheme behind this, or anything having to do with backwards compatibility or perf improvements, a .cpp file is simply expected to contain C++ code. Both compilers use the same back-end (code generator and optimizer) so there will not be any great difference if you compile C code with the C++ compiler.
The /EH compile option only does something if you create C++ objects in your code and the compiler can tell that an exception might be thrown. If the codebase is largely C based then it won't make any difference. The actual cost of /EH is very low, a few cpu cycles to register an exception filter. There's no cost when exception handling uses function tables but yours is almost surely too old to support that (/SAFESEH or x64 code).
If you just took over a large project then tinkering with the compiler settings ought to be a low priority. Get to know the codebase first before you start changing options that may break the code and will give you a hard time debugging the problem. Or to put it another way, avoid looking for the Deus Ex Machina that will make it look like you made a great achievement in very little time. Using a profiler will get you much more bang and a better insight.
Related
Here is my scenario:
I,m working on an embedded linux system and getting a shared library written in C++. It works well except that libstdc++ is required, which means an extra 1M memory is occupied. I want to convert the shared library to C so that 1M memory will be saved.
I know how to convert C++ code to C by hand but it will be really boring. So I searched for solution and getting a similar question: Use Clang to convert C++ to C code. However the generated code is not readable. I want to get maintainable C source code to obsolete the original C++ code.
I'm a newbie at Clang. I have learnt that Clang can be used to build a tool that processes code. My question is:
Is it possible using Clang to achieve my goal?
If it is possible, how can I do that? To be more specific, how can I use Clang to remove code blocks wrapped by macro as the first step?
In practice converting (semi-automatically) genuine C++ code to maintainable C code is not realistic.
I want to get maintainable C source code to obsolete the original C++ code.
You certainly won't get maintainable and readable and portable C code (for instance, as soon as standard containers are used in C++; their template expansion is not readable, and probably not portable to something with different word size, alignment, endianness ...). You could transform LLVM IR to some unportable and unreadable subset of C.
It works well except that libstdc++ is required, which means an extra 1M memory is occupied
Perhaps you could try linking (everything) statically; maybe only a part of libstdc++ is used in your particular application.
BTW, you could get GIMPLE from GCC, and convert that GIMPLE to unreadable C code (perhaps by customizing GCC with a plugin or a GCC MELT extension).
You might also try to compile and link with link time optimization, e.g. with -flto -Os (with recent GCC or Clang).
Don't forget that development efforts also has some costs. Is it worth spending a whole year of work (or more) for a team of a few developers to win a few hundred kilobytes? In most cases upgrading the hardware to something with slightly more memory would cost a lot less. YMMV
I have a huge amount of code written in Pascal and I need to use it in a C++ application running on an embedded PC with ARM9 processor. My idea was cross compiling Pascal code to dll libraries which I wanted to include in my C++ app. I tried to install Lazarus but I can't get work its cross compiler and I tried to install compiler directly to the embedded PC with similar result. C++ cross compiler works perfectly. Is there any way how to get Pascal code working in C++ application on different platform? I will provide any additional info if needed.
Additional info:
the embedded pc is for use in extremely low temperatures so it has low ram (32MB) running a trimmed Linux and there is only a little free space left on its flash memory (i have to use the SD card for all files)
I don't think anyone can conclusively answer your question, but some hints:
You will need to find a way to communicate between the C++ and Pascal code. This may simply be a case of defining any interface function as a C or C++ style function. But for example strings in Pascal are often NOT standard C or C++ style strings, so will need some extra handling to work out right. Structs (RECORD in pascal) and classes will require even more careful handling as to how they interface between the C++ and Pascal code - in most cases, it will become a full marshalling solution (that is, convert to a byte-stream, and then convert back to correct type at the other end).
Cross compilation of the Pascal code relies on having a Pascal compiler that matches your Pascal code AND your target. If you can't compile your code to the correct target, all other parts of the project will fail... There is a "standard" for Pascal, but most compilers have a range of extensions.
Have you considered making the Pascal code a standalone application that produces results as a file, rather than directly interfacing to the C++ code? Reading a file that you can control the format of can be a much easier solution than trying to interface one language to another.
I am using C++ (in xcode and code::blocks), I don't know much.
I want to make something compilable during runtime.
for eg:
char prog []={"cout<<"helloworld " ;}
It should compile the contents of prog.
I read a bit about quines , but it didn't help me .
It's sort of possible, but not portably, and not simply.
Basically, you have to write the code out to a file, then
compile it to a dll (invoking the compiler with system), and
then load the dll. The first is simple, the last isn't too
difficult (but will require implementation specific code), but
the middle step can be challenging: obviously, it only works if
the compiler is installed on the system, but you have to find
where it is installed, verify that it is the same version (or
at least a version which generates binary compatible code),
invoke it with the same options that were used when your code
was compiled, and process any errors.
C++ wasn't designed for this. (Compiled languages generally
aren't.)
The short answer is "no, you can't do that". C and C++ were never designed to do this.
That's pretty much also the long answer to the actual question, but I'll expand a bit on a few ideas.
The code, as compiled by the compiler is pretty certainly not trivial to add things to. There are a few techniques that can be used to "add more code" to a program:
Add a dynamic shared library (DLL), which contains code that has been compiled separately to the existing code. You could of course also have code in your program to output some code, compile this code with the compiler, link it into a dynamic library, and load it in your code.
You could build your own little code-generator that generates machine code in a chunk of memory. Note that you probably need to call a "special" memory allocation function, as "normal" memory allocations are typically not allowed to be executed - you need to allocate "with execute permission" - VirtualAlloc in Windows does have such a flag, and mmap in Linux/Unix flavours does too. And of course, you pretty much have to "be a compiler" to achieve this.
You could naturally also invent your own interpreted language, which would allow your program to load in for example a text-file with commands/instructions to be executed, or contain text inside the program for execution with this language.
But like I said to start with, this is not what C and C++ (and most other compiled languages) were meant for, so it's not going to be as simple as "stick some C++ code in a string, and make it run".
It depends why you want to do this.
If it's for efficiency reasons - you know what a function does only at run time, but it has to be very efficient - then what was already suggested (writing to a file, compiling to a dll / so and dynamically loading it) is your best option.
BUT if the reason you want this is to allow for user-input behaviour, say a general function your read from a database (behaviour or a unit ingame? value of a field in a plot?) - or more generally you just want to change / augment behaviour at runtime with little concern for efficiency, I recommend using an outside scripting language like lua, which easily interacts with your compiled C++ code.
The C and C++ languages compile to binary machine code, unlike Java and C# which generate instructions for a 'virtual machine' or interpreted scripting languages such as JavaScript. The compilation of C++ is performed by a separate executable, the compiler, which is not incorporated into the resulting executable.
So the language does not have any built in "eval" capability to translate further code once compilation is finished.
It's not uncommon for new C/C++ programmers to think they need to do this, but they typically don't. Perhaps you could expand further on what you're actually looking to do.
But if you do actually need to be able to do this, your options are:
Write code to compile a new executable with the new code and then run the resulting program.
Write a simple parser and "virtual machine" of your own,
Look at incorporating an embedded scripting/interpreted language such as Lua,
Try and wrap your head around integrating CINT,
See also: Scripting language for C++
guys I want to start programing with C++. I have written some programs in vb6, vb.net and now I want to gain knowledge in C++, what I want is a compiler that can compile my code to the smallest windows application. For example there is a Basic language compiler called PureBasic that can make Hello world standalone app's size 5 kb, and simple socket program which i compiled was only 12kb (without any DLL-s and Runtime files). I know it is amazing, so I want something like this for C++.
If I am wrong and there is not such kind of windows compiler can someone give me a website or book that can teach me how to reduce C++ executable size, or how to use Windows API calls?
Taking Microsoft Visual C++ compiler as example, if you turn off linking to the C runtime (/NODEFAULTLIB) your executable will be as small as 5KB.
There's a little problem though: you won't be able to use almost anything from the standard C or C++ libraries, nor standard features of C++ like exception handling, new and delete operators, floating point arithmetics, and more. You'll need to use only the features directly provided by WinAPI (e.g. create files with CreateFile, allocate memory with HeapAlloc, etc...).
It's also worth noting that while it's possible to create small executables with C++ using these methods, you may not be using most of C++ features at this point. In fact typical C++ code have some significant bloat due to heavy use of templates, polymorphism that prevents dead code elimination, or stack unwinding tables used for exception handling. You may be better off using something like C for this purpose.
I had to do this many years ago with VC6. It was necessary because the executable was going to be transmitted over the wire to a target computer, where it would run. Since it was likely to be sent over a modem connection, it needed to be as small as possible. To shrink the executable, I relied on two techniques:
Do not use the C or C++ runtime. Tell the compiler not to link them in. Implement all necessary functionality using a subset of the Windows API that was guaranteed to be available on all versions of Windows at the time (98, Me, NT, 2000).
Tell the linker to combine all code and data segments into one. I don't remember the switches for this and I don't know if it's still possible, especially with 64-bit executables.
The final executable size: ~2K
Reduction of the executable size for the code below from 24k to 1.6k bytes in Visual C++
int main (char argv[]) {
return 0;
}
Linker Switches (although the safe alignment is recommended to be 512):
/FILEALIGN:16
/ALIGN:16
Link with (in the VC++ project properties):
LIBCTINY.LIB
Additional pragmas (this will address Feruccio's suggestion)
However, I still see a section of ASCII(0) making a third of the executable, and the "Rich" Windows signature. (I'm reading the latter is not really needed for program execution).
#ifdef NDEBUG
#pragma optimize("gsy",on)
#pragma comment(linker,"/merge:.rdata=.data")
#pragma comment(linker,"/merge:.text=.data")
#pragma comment(linker,"/merge:.reloc=.data")
#pragma comment(linker,"/OPT:NOWIN98")
#endif // NDEBUG
int main (char argv[]) {
return 0;
}
I don't know why you are interested in this kind of optimization before learning the language, but anyways...
It doesn't make much difference of what compiler you use, but on how you use it. Chose a compiler like the Visual Studio C++'s or MinGW for example, and read its documentation. You will find information of how to optimize the compilation for size or performance (usually when you optimize for size, you lose performance, and vice-versa).
In Visual Studio, for example, you can minimize the size of the executable by passing the /O1 parameter to the compiler (or Project Properties/ C-C++ /Optimization).
Also don't forget to compile in "release" mode, or your executable may be full of debugging symbols, which will increase the size of your executable.
A modern desktop PC running Windows has at least 1Gb RAM and a huge hard drive, worrying about the size of a trivial program that is not representative of any real application is pointless.
Much of the size of a "Hello world" program in any language is fixed overhead to do with establishing an execution environment and loading and starting the code. For any non-trivial application you should be more concerned with the rate the code size increases as more functionality is added. And in that sense it is likley that C++ code in any compiler is pretty efficient. That is to say your PureBasic program that does little or nothing may be smaller than an equivalent C++ program, but that is not necessarily the case by the time you have built useful functionality into the code.
#user: C++ does produce small object code, however if the code for printf() (or cout<<) is statically linked, the resulting executable may be rather larger because printf() has a lot of functionality that is not used in a "hello world" program so is redundant. Try using puts() for example and you may find the code is smaller.
Moreover are you sure that you are comparing apples with apples? Some execution environments rely on a dynamically linked runtime library or virtual machine that is providing functionality that might be statically linked in a C++ program.
I don't like to reply to a dead post, but since none of the responses mentions this (except Mat response)...
Repeat after me: C++ != ( vb6 || vb.net || basic ). And I'm not only mentioning syntax, C++ coding style is typically different than the one in VB, as C++ programmers try to make things usually better designed than vb programmers...
P.S.: No, there is no place for copy-paste in C++ world. Sorry, had to say this...
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.