Re: Helper functions
On Thu, 13 Nov 2008 09:27:34 -0400, "Jeova Almeida"
<jeovaalmeida@yahoo.com> wrote:
Hello,
I'm creating some helper functions, like:
CString GetLastErrorMessage(DWORD dwLastError )
{
LPVOID lpMsgBuf = NULL;
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwLastError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
// Default language
(LPTSTR) &lpMsgBuf, 0, NULL );
CString str = (LPCTSTR)lpMsgBuf;
if( lpMsgBuf != NULL )
LocalFree(lpMsgBuf);
I think you need to do some error checking before initializing str.
return str;
}
I see two options for that:
a) Create a CHelper class with a static GetLastErrorMessage() method
or
b) Create an class-independent, generic function
In previous projects, opting for option b, I coded the functions in a file
named Helpers.h and inserted lots of functions like the one above using the
static keyword, and #including Helpers.h in each file which needed the
functions contained in the helpers.h file. This worked fine.
But duplicated a lot of code.
My questions are:
a) Using the static keyword as stated above and #including the Helper.h file
in, let's say, 20 other classes which depend on the functions contained in
the Helpers.h file will actually include the contents of the Helpers.h file
in all those 20 other classes, swelling the size of the output file (.exe)?
If by "classes" you mean "source files", the answer is "yes".
b) Thinking the question a would be true, I thought of creating a Helper.cpp
file with all the implementation and a Helper.h with all the declaration,
without the static keyword. By doing so, I got the link error LNK2019 saying
the functions are unresolved externals. The Helper.cpp file is part of the
project, and the classes which uses the functions have the Helper.h
#included. Why the functions are considered unresolved?
No idea. The modern C++ way to do this is to use namespaces, e.g.
// .h file
namespace CStringHelper {
CString GetLastErrorMessage(DWORD dwLastError);
// Other declarations...
}
// .cpp file
namespace CStringHelper {
CString GetLastErrorMessage(DWORD dwLastError)
{
...
}
// Other definitions...
}
--
Doug Harrison
Visual C++ MVP