简体   繁体   中英

How does Windows API work?

It seems we are free to use Windows API simply by including header files needed. However, i couldn't make myself understand how this is possible given that header files do not have function definitions but declarations, which is supposed to be considered as an error in that it lacks implementation details. In what way does a compiler locate an implementation detail and map it into memory?

The Windows API is implemented in DLLs that are installed when you install Windows. Those DLLs are in the System directory and have names like User32.dll, Kernel32.dll, etc.

As you correctly noted, the Windows API header files supplied with your compiler contain only the declarations. When your C program calls one of those functions (or any other function that's identified in a header file but not actually compiled with your project), the compiler places a record in the generated object file that says, in effect, "I need to call a function called GetWindowRect (or whatever the name of the function you called)."

The linker is what actually resolves the names. If you look at your linker options, you'll see that it's linking some libraries like User32.lib, Kernel32.lib, etc. Those libraries contain compiled functions that are little more than stubs--code that causes the corresponding DLL to be loaded, and then calls the function in the DLL.

It's a little bit more involved than that, but that's the general idea. In summary:

  1. You include the Windows API header files.
  2. Your code makes a call to one or more Windows API functions that are declared in those header files.
  3. The compiler makes a note for the linker to resolve those API function calls.
  4. The linker resolves the calls by finding the stub functions in the libraries that you specify on the linker command line.
  5. At runtime, a call to one of those functions causes the corresponding DLL to be loaded, and then control is branched to the function in the DLL.

It works the same as any other library, for example C stdlib - your program only needs to 'know' the prototypes of functions (and thus the underlying symbol names). After compilation comes linking - that's when the symbols (function definitions) that are missing get 'linked' with a correct library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM