Introduction
I have to maintain code that was originally written during the heyday of Visual Studio 6.0, but that also needs to be used in newer projects that are compiled under Visual Studio 2005. The files in question are shared between two programming teams - one is writing VC6 code, and the other is writing VS2005 code - the projects are different but we're all about code re-use. I'm sure there are at least three other people out there in CP-land that have the same requirements.
Specifically, our code invariably includes the use of several standard I/O functions like sprintf
, printf
, et al, and we all know what happens when you try to use these functions in VS2005 - the compiler pukes out hundreds (or thousands) of warnings about the functions being deprecated. The quick fix is to include the appropriate preprocessor definition in the program settings, but that's just plain laziness.
How I Solved The Problem
My technique was to write a wrapper function that will use the appropriate version of the stdio function, depending on what version of the compiler you're using. This really cleaned up my code in terms of readability because the preprocessor code is all in one place instead of being scattered through the code (about 50 instances in just one file).
#define _VS2005_
#if _MSC_VER < 1400
#undef _VS2005_
#endif
int sprintf_ex(char* sDest, int nSize, char* sFormat, ...)
{
va_list argList;
va_start(argList, sFormat);
int nCount = 0;
#ifdef _VS2005_
nCount = _vsnprintf_s(sDest, nSize, nSize-1, sFormat, argList);
#else
nCount = _vsnprintf(sDest, nSize, sFormat argList);
#endif
va_end(argList);
return nCount;
}
Implementation might look like this:
char sTest[1024];
int nCount = sprintf_ex(sTest, sizeof(sTest), "%d %s", 5, "Test");
It would be a simple exercise to wrap other functions in a similar fashion, but since we didn't have a need, I didn't write the code. This should be a simple exercise for most C++ programmers, given the example above.
What?! No Sample Code To Download?!!!
Oh please. As you can see, it's just a function wrapper that demonstrates a simple technique. I'm not going to go through the hassle of preparing a sample project for something that you simply have to copy/paste into an existing source file to try out. Besides, you're all supposed to be programmers - create a test project if you have to.
What?! No Screen Shots To Gawk At?!?!
You guys are funny. Now it's my turn to be funny.
Disclaimer
I do not code in managed C++, so I don't know if this will work in that environment.