if windows.h collide with STL... ...

Started by
10 comments, last by yckx 16 years, 6 months ago
so, how can I solve the problem below. Since max is both defined in <windows.h> ( as a macro) and <algorithm>, if I compile the code below, VC will automatically resolve the max as the macro defined in <windows.h>. However I do want to use the STL version. Can anyone give me a tip :) ( I have to use <windows.h>, so removing it is not an option )

#include <iostream>
#include <algorithm>
#include <windows.h>

using namespace std;

void main()
{
	int a, b, c;
	a = 90;
	b = 9;
	c = 8;
	cout << max( a, max( b, c ) ) << endl;
}

Advertisement
Define the NOMINMAX macro before including windows.h.
So:
#define NOMINMAX#include <windows.h>
Type #define NOMINMAX before #include <windows.h>. Open up Windows.h for a list of such flags you can set.

EDIT: Beaten by seconds. ;)
Alternatively you could remove the line: using namespace std;
Then whenever you want to use the STL version of min you'd type: std::min
Quote:Original post by dmatter
Alternatively you could remove the line: using namespace std;
Then whenever you want to use the STL version of min you'd type: std::min
That won't help. They are defined as macros.
Quote:Original post by dmatter
Alternatively you could remove the line: using namespace std;
Then whenever you want to use the STL version of min you'd type: std::min

This doesn't work. I was going to suggest it myself but ran a quick test before I did so.
Quote:Original post by dmatter
Alternatively you could remove the line: using namespace std;
Then whenever you want to use the STL version of min you'd type: std::min


This does work although you have to do it a little different.
 (std::max)(a.b)
Quote:Original post by implicit
Quote:Original post by dmatter
Alternatively you could remove the line: using namespace std;
Then whenever you want to use the STL version of min you'd type: std::min
That won't help. They are defined as macros.

So they are, I didn't realise. I can see why they did it that way but it's pretty icky.
Thanks, guys! So to make a conclusion, there're two ways to solve this:
1) as DaBono & Kylotan said, use macro NOMINMAX before #include <windows.h>
2) as CmpDev suggested : (std::max)(a, b);

The point here is no matter what you do, if you point the cursor to the line in your code, VC will always indicate that it is a macro, however if you check the disassembly, you can see the real code. Maybe this is one case that VC is out of the rule of WYSIWYG, hope they could improve this in the new version ;)
Quote:Original post by jhq
2) as CmpDev suggested : (std::max)(a, b);

No, this won't work because max is defined as a macro in windows.h, and the preprocessor will expand it anyway. It's not really a namespace issue, in this case.

Although I agree that you should prefer to avoid using namespace std and use std::max as well as #define NOMINMAX.

This topic is closed to new replies.

Advertisement