Wednesday, April 9, 2008

compiling with std::min, std::max in Visual Studio 2008

I had a program which was working well in Visual Studio 6.0. I wanted to upgrade my compiler to VS9.0.  When I compiled the code (snippet listed below), I got the following error message.

void
SVD::Rank( int inRank )
{
mRank = inRank;

int max_rank = std::min( mS.size(), mU.size() ); <-- Line 329
if( mRank < 0 || mRank > max_rank )
{
mRank = max_rank;
}

} // SVD::Rank





1>------ Build started: Project: sci, Configuration: Debug Win32 ------
1>Compiling...
1>SVD.cpp
1>d:\projects\dev\libs\sci\svd.cpp(329) : error C2589: '(' : illegal token on right side of '::'
1>d:\projects\dev\libs\sci\svd.cpp(329) : error C2059: syntax error : '::'
1>Build log was saved at "file://d:\projects\dev\libs\sci\Debug\BuildLog.htm"
1>sci - 2 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 1 up-to-date, 0 skipped ==========



When I googled for this error, I found the following article from DevX.com (http://www.devx.com/tips/Tip/14540).




The Standard Library defines the two template functions std::min() and std::max() in the <algorithm> header. In general, you should use these template functions for calculating the min and max values of a pair. Unfortunately, Visual C++ does not define these function templates. This is because the names min and max clash with the traditional min and max macros defined in <windows.h>. As a workaround, Visual C++ defines two alternative templates with identical functionality called _cpp_min() and _cpp_max(). You can use them instead of std::min() and std::max().To disable the generation of the min and max macros in Visual C++, #define NOMINMAX before #including <windows.h>.




Interesting, this solution was not really doable for me as I was compiling with ACE libraries (TAO 1.5a) with STLport (STL 5.1.5).  With ACE, I would be including <ace/OS.h> instead of <windows.h> and inserting #define NOMINMAX before #include <ace/OS.h> is not a good solution for me.  So I did the following.  Wherever, I use std::min, std::max, I had included <algorithm> header, but before that inclusion of <algorithm> I had forcible undefined min and max symbols like the following




#undef min
#undef max
#include <algorithm> // for std::sort, std::min, std::max



I got my source compiled without errors now.

2 comments:

Anonymous said...

THANK YOU VERY MUCH!!!

Anonymous said...

This post is still helpful. Many thanks for the legwork.