1

I am using Visual Studio Community 2017 to code c++. When I run the following code everything works fine.

#include "pch.h"
#include<Windows.h>
#include<Psapi.h>
#include <iostream>
#include <conio.h>

int main()
{

    std::cout << "Really!! How do you do it?";
    _getch();
}

But if I change the order of #includes by including psapi.h before Windows.h, compiler goes badass and throws 198 errors at me, which surprisingly(maybe only to me) includes Identifier "BOOL" is undefined. Why is this happening?

Chief A
  • 510
  • 10
  • 24
  • 3
    Probably because `Psapi.h` needs some definitions made in `Windows.h` like `BOOL`? – πάντα ῥεῖ Sep 17 '18 at 12:20
  • The error is pretty self-explanatory, did you see where `BOOL` is defined and why this would need to be defined prior to it's usage? – EdChum Sep 17 '18 at 12:23
  • 2
    `Psapi.h` should include `Windows.h` itself to avoid such problems. – Yksisarvinen Sep 17 '18 at 12:29
  • 1
    The author(s) of psapi.h seem to have fostered an header file *order dependency*, which frankly is just wrong. It's not your fault. The only header psapi.h internally includes is winapifamily.h, which itself does *not* include windows.h, windef.h, etc, any number of which would pull in the proper macros/typedefs for dependent use within psapi (like BOOL, WINAPI, etc). If there's a reason the author(s) did this outside of flat-out laziness or oversight, I can't think of it. You'll have to include it yourself prior to psapi.h – WhozCraig Sep 17 '18 at 12:37

2 Answers2

6

Since Psapi.h's include tree is trivial, I'm going to exemplify.
Everything relies on VStudio 2015 (Community) (v14.0.25431.01 Update 3) and Windows Kits 8.1 (? funny, because v10 is there too) files (with default env vars and preprocessor definitions):

  • BOOL is defined in minwindef.h (#157: typedef int BOOL;)

  • Psapi.h only includes one file (#27: #include <winapifamily.h>)

    • winapifamily.h doesn't include any other file

So, when reaching Psapi.h (#87: BOOL WINAPI EnumProcesses (...), the compiler doesn't know anything about BOOL, so it complains.

Windows.h includes minwindef.h (indirectly, via windef.h), and that's why it works when you include it before Psapi.h.

Personally, I think it's a bug in Psapi.h, since it's not self contained, but there might be a good reason (that I'm not aware of) for that.
Anyway, if this is indeed a bug, it wouldn't be MS's 1st one :)

#include <Windows.h>
#include <WinSock2.h>

// main present just for rigorosity's sake
int main() {
    return 0;
}
CristiFati
  • 38,250
  • 9
  • 50
  • 87
0

to answer the question, I know this is DATED but the issues persist today. You need the following:

#include "stdafx.h"
#include <stdbool.h>
#include <Windows.h>
#include <stdlib.h> 
#include <psapi.h>

After stdlib.h was included, the errors were gone.