Trailing spaces after backslash delimiter – Programmers nightmare.

31 03 2008

Icon Description
Usually we used to have spaces after semi columns. Since C++ ignore whitespace, its not a problem. But in Visual C++ 6.0 that is not the case always. If you put spaces after the backslash delimiter(\), it will become one of the worst bugs that you encounter.

icon_underthehood.jpg
Usually we use backslash delimiter to concatenate lines – mostly while writing macros. See the following macro.

#define INCREMENT_AND_DECREMENT( Value ) \
    Value = Value + 1; \ » » »
    Value = Value - 1;

In the macro, instead of » char, put some tab or space and then compile. You will get a strange error as follows.

error C2501: 'Value' : missing storage-class or type specifiers

Icon How Can I Do It?
One of the defensive mechanism is – always enable “View whitespace” by pressing Ctrl+Shift+8. So take care next time and don’t spend hrs on these silly bugs as I did years before.


Note that its just a implementation behavior in Visual C++ 6.0 and may not found in other compilers or upcoming Visual C++ versions.

Thanks to Hemant for pointing out my implicit biasing towards VisualStudio 6.0. I forgot to specify that its just a Visual studio behavior.

intermediateseries.jpg
Targeted Audience – Intermediate.





Visual C++ Preprocessor null directive

30 03 2008

Icon Description
Well, add an empty # symbol to your #include list and compile the project. For e.g. see the following #include list.

#include “stdafx.h”
#include “Dialog.h”

#
#include “DialogDlg.h”

It will compile without showing any errors. Weird?

icon_underthehood.jpg
The single “#” in a line is called null directive. It has no effect. Indeed, its not a bug. 😉
But i can’t find the answer for question… What is the purpose?





Reduce iostream compilation dependency by using iosfwd

30 03 2008

Icon Description
For making our classes compatible with cin and cout, we usually over load << and >> operators. And if such classes are the part of our modules interface, the iostream header file should be added to the interface header of our module. It makes compilation overhead for the classes those use our exported class. Please see the following code block.

#include <iostream>

class IMyInterface
{
public:
    // Overloaded << operator.
    std::ostream& operator<<( std::ostream& os );
};

Icon How Can I Do It?
You can easily reduce the compile time dependency of iostream header by using iosfwd. It contains forward declaration of several template classes defined in iostream. Please check MSDN for more details. Don’t forget to include iostream in your cpp files, since iosfwd contains just forward declarations.

#include <iosfwd>

class IMyInterface
{
public:
    // Overloaded << operator.
    std::ostream& operator<<( std::ostream& os );
};




List the loaded modules in your crash report.

29 03 2008


In crash reports, usually we see a list of loaded modules. While writing Error Handler frameworks, for dumping crash reports we too need to get list of loaded modules which will make the debugging tasks easier. But how can we find out the loaded modules? You can use EnumerateLoadedModules() function to enumerate the loaded modules.


You can use EnumerateLoadedModules() function to enumerate the loaded modules. For calling EnumerateLoadedModules() we need provided a callback function pointer. The EnumerateLoadedModules() will send the loaded module information as callback to that provided function. Please see the following code

#include <Dbghelp.h>  

// Callback function.
BOOL CALLBACK EnumerateLoadedModulesProc( PSTR ModuleName,
                                          ULONG ModuleBase,
                                          ULONG ModuleSize,
                                          PVOID UserContext )
{
    // Print the module name.
    cout << ModuleName << endl;
    return TRUE;
}  

int main(int argc, char* argv[])
{
    // Enumerate loaded modules.
    EnumerateLoadedModules(
       GetCurrentProcess(),	// Process Handle
       // Callback function pointer
       (PENUMLOADED_MODULES_CALLBACK) EnumerateLoadedModulesProc,
       0 );	// User context.   

       return 0;
}

Add beauty and complexity to your crash report by listing out the module names 😉





How to remove unwanted libraries from project settings.

28 03 2008

Icon Description
Usually in the project settings, we will provide a list of .lib files that the project needs to compile. For small projects it’s manageable. But for big project which uses a lot of 3ed party frameworks, the .lib list can grow and may contain unwanted libraries which are not used any more. Even though an extra library in project setting is harmless, it may end up messing up the project setting. Some clients even have strict project setting rule – project settings should not include unused libraries.

Icon How Can I Do It?
One method is error and trial. Remove each library by hand and compile. If you won’t get any error then you can remove it. Or else you should try Masters Method!

1) Take project settings.
2) Take Link tab.
3) In the “project options” editbox add the switch – /verbose
4) Rebuild the project
5) Now in the output window you can see a lot of messages other than normal build.
6) Find the pass 2 section in the output messages. It will be almost same as follows

Start Pass2
   StdAfx.obj
   Hello.obj
   kernel32.lib(KERNEL32.dll)
   kernel32.lib(KERNEL32.dll)
   kernel32.lib(KERNEL32.dll)
   ...
   LIBCD.lib(_freebuf.obj)
   LIBCD.lib(close.obj)
   LIBCD.lib(commit.obj)
   LIBCD.lib(fclose.obj)
End Pass2

7) In the pass 2 section, linker will emit all used libraries.
8 ) In the above e.g. the lib files needed
are “kernel32.lib” and “LIBCD.lib”
9) So you’ve found the required library files!
10) Add them to “object/library modules:” editbox of linker settings.
11) Don’t forget to enable “ignore default libraries” options of linker. Because by default the linker links a set of default libs to the project. Those libs are no more needed!
12) Your project is free from unwanted libraries.

Now the choice is yours.Want to go for “Error and trial” or “Masters Method”? 😉

advancedseries.jpg
Targeted Audience – Advanced.





GetCurrentThread() returns pseudo handle, not the real handle.

26 03 2008

Icon Description
For getting our thread handle, we usually call GetCurrentThread() api. But actually it returns a pseudo handle. A pseudo handle, is a special handle which represents the handle of current thread which uses it. Please see the following e.g. for more clarify.

1) Thread A gets its threadID by calling GetCurrentThread and Passed to Thread B.
2) Thread B needs to terminate Thread A. So it calls TerminateThread( handle passed by Thread A ).
3) But instead of terminating Thread A, Thread B will be terminated, because the handle passed by Thread A was pseudo and it will become Thread B’s handle when Thread B uses it.

Debug one GetCurrentThread() call and GetCurrentProcess() call and watch its return values. You can see what they returns are follows,

  • GetCurrentThread() – 0xfffffffe
  • GetCurrentProcess() – 0xffffffff

Ofcourse pseudo… isn’t it ?

Icon How Can I Do It?
For getting a real handle which represents your thread, create a duplicate handle by calling DuplicateHandle(). Please see the code block below.

HANDLE hRealHandle = 0;
DuplicateHandle( GetCurrentProcess(), // Source Process Handle.
                 GetCurrentThread(),  // Source Handle to dup.
                 GetCurrentProcess(), // Target Process Handle.
                 &hRealHandle,        // Target Handle pointer.
                 0,                   // Options flag.
                 TRUE,                // Inheritable flag
                 DUPLICATE_SAME_ACCESS );// Options
// Now the hRealHandle contains a real handle for your thread.




How to skip a class or library from being profiled?

26 03 2008

Icon Description
We used to run profiler for performance tuning. By using profiler, you can check – function timing, function coverage etc. By default profiler profiles the entire modules. But how can we skip a particular user library or class from profiling?

Icon How Can I Do It?
There is a setting file named profile.ini, where profiler keep its settings.
For skipping a user library just add a line like this.
exclude:myuser.lib

Assume you have a class named CHighPerfomance and want it to be skipped from profiling, then add the following line.
exclude:CHighPerfomance.obj

Icon - Where is it?
The profiler setting file is located at
<VisualStudioDir>\VC98\bin\PROFILER.INI