Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is #include <Windows.h> bad practice?

Tags:

c++

winapi

I think it's universally accepted that #include <bits/stdc++.h> is bad practice, in part because it parses and includes every standard header, which is almost always unnecessary (it's also nonportable, but that's beyond my point). It's even worse when combined with using namespace std; because now you have a ton of common names in your namespace, like next.

Yet, it seems that #include <Windows.h> is mostly deemed to be OK (it's used by most Win32 programs I've seen), even though it conceptually does the same thing as a combination of #include <bits/stdc++.h> + using namespace std;.

According to Wikipedia:

windows.h is a Windows-specific header file for the C and C++ programming languages which contains declarations for all of the functions in the Windows API, all the common macros used by Windows programmers, and all the data types used by the various functions and subsystems. It defines a very large number of Windows specific functions that can be used in C.

Why is this the case? Is it not possible to include specific headers we use and not include <Windows.h>?

like image 359
Ayxan Haqverdili Avatar asked May 20 '20 19:05

Ayxan Haqverdili


2 Answers

Msdn documentation explicitly tells you (a) in which header file a function is declared and (b) which header file you are supposed to include.

Most functions tell you to include windows.h, for example SendMessage

Some function, that were added later or have very specific use cases, are only available through other header files, for example SetupDiEnumDeviceInfo.

So no, it is not bad practice to follow their advice. However, I strongly recommend disabling some parts of it before including via macro, e.g.

#define NOMINMAX
#include <Windows.h>

because otherwise you will get a min and a max macro that will interfere with std::min and std::max.

like image 185
Timbo Avatar answered Oct 11 '22 23:10

Timbo


bits/stdc++.h is a compiler-specific header. If you compile your code with a different compiler it may or may not exist. It's not part of standard C++. It's a shortcut for access to the C++ standard library.

windows.h is an operating-system specific header. If you're compiling for Windows you need it, and every compiler that supports Windows will be okay with it. It doesn't necessarily come with the compiler; it comes with the Windows Software Development Kit. It provides access to the Windows API.

You might be able fine-tune your #include directives under Windows, but Windows is such a mess that unless you really want to spend time digging into it, you're better off just using windows.h.

like image 2
Pete Becker Avatar answered Oct 11 '22 23:10

Pete Becker