Incorrect value for global integer variable inside a keyboard hook

I have declared a global integer variable in my program. Whenever I try to access this variable inside a keyboard...

hook function, I get the value of the variable as 0. But when accessed from any other function, I am getting the correct value. What could be the reason for this? I'm assuming that your keyboard hook is being loaded into another process when answering the question, which should be the case. The issue is that in Win32, global variables are not shared across processes by default. Fortunately, there's a way to mark specific sections of the Portable Executable (PE) file as shared across all address spaces.

What you'll need to do is create a new section in your DLL (dynamic link library) by specifying the name of the section using the #pragma data_seg directive like the following. For this example, I'll name the segment .RIJU, since the name can only be 8 characters long, including the initial period. You don't need the period on the front, but it's traditional.

  • Create and name the data segment.
    #pragma data_seg (".RIJU")
  • Declare my global that I want shared across all processes
    static int g_iSharedVariable = 0 ;
  • Close the data segment.
    #pragma data_seg ( )
  • Once you've got your data segment, you'll need to tell the linker that the segment is to be marked shareable across all processes. The first way is to specify the segment as sharable in the linker definition file (.DEF). The following is a complete .DEF file that will share the .RIJU section. Note that I made up the exported function name.


  • ; The shared data setting.
    .RIJU Read Write Shared
  • While I prefer using the .DEF file to specify the shared section, you can also use the /SECTION LINK.EXE switch. My preference for the .DEF file is that you're guaranteed to ensure the section gets marked correctly, even if someone moves your code to a different DLL and forgets to update the build settings. If you were to use the linker, the command line switch for the above example would be the following, which you can enter in the Command Line section of the Linker property pages in Visual Studio.NET. The "rws" stands for read, write and shared.


    This was first published in December 2002

    Dig Deeper on Enterprise Infrastructure Management



    Find more PRO+ content and other member only offers, here.

    Have a question for an expert?

    Please add a title for your question

    Get answers from a TechTarget expert on whatever's puzzling you.

    You will be able to add details on the next page.



    Forgot Password?

    No problem! Submit your e-mail address below. We'll send you an email containing your password.

    Your password has been sent to: