View Single Post
  #38 (permalink)  
Old 22nd January, 2004, 05:14 AM
Gizmo's Avatar
Gizmo Gizmo is offline
Chief BBS Administrator
Join Date: May 2003
Location: Webb City, Mo
Posts: 16,178
Send a message via ICQ to Gizmo Send a message via AIM to Gizmo Send a message via MSN to Gizmo Send a message via Yahoo to Gizmo Send a message via Skype™ to Gizmo

Discovered another one of those 'screwball' compiler optimizations that I love today....

Consider a class in C++. You write the declaration (.h) and the implementation (.cpp). Now, some functions in the implementation are very simply one liners, so you go ahead and write the implementation as part of the definition. As an example, you do the following in the header file:

int Class::Version() {return DEFINED_VERSION;}

So far, so good. This compiles and everything seems hunky-dory. The problem here lies in the fact that many optimizing compilers will take this implementation and, because it is defined in the header file, is a simple one-liner, and is returning a constant, instead of compiling the call-return sequence that would be used for a regular function, this call gets compiled into a hard constant in the final application. So far, so good.

At some later point you decide that this class is usefull enough to make into a DLL, so that you don't have to include this code in every app that uses it. Since the version checking call above is compiled as a hard constant in the app, you can end up using a dll with a version other than that what you are checking for and NOT KNOW IT! The only way to solve this problem is to take the one-liner out of the header and put it into the implementation, so that it is part of the dll and the link library.

I encountered this little gem today and spent the better part of 2 hours trying to figure out what was going on. It was only when I looked at the assembly output of the compiler that I realized what had happened. The nasty part about this is that when I ran the code in debug mode, everything worked right. That is because, generally, when you compile an application in debug mode, all optimizations are disabled.

Just thought that you guys might find this real world example of how compilers can sometimes screw you to be helpful.
Reply With Quote