5

MFC has defines such as

#ifdef UNICODE
#define DrawText  DrawTextW
#else
#define DrawText  DrawTextA
#endif // !UNICODE

However I am using a library which also has DrawText() function and I guess MFC defines change that as well and I am getting linker error for this call because obviously the library has no function with the name DrawTextW(...)

How can I make the library function work in my MFC application?

2 Answers 2

5

This is not MFC, but rather the Windows API. The prescribed way to work around macros that shadow other symbols is to temporarily disable the macro:

// Temporarily undefine the DrawText macro
#pragma push_macro("DrawText")
#undef DrawText

// Call your version of DrawText
DrawText( ... );

// Re-enable the macro
#pragma pop_macro("DrawText")

#pragma push_macro and pop_macro are necessary to not break the Windows SDK headers.

The same scheme should be applied in the header and implementation files for your class. If you cannot change the header file for this class, you need to wrap the #include directive in a push/undef/pop sequence:

#pragma push_macro("DrawText")
#undef DrawText

#include "my_header.h"

#pragma pop_macro("DrawText")
1

A simple preprocessor hack should do the job. But you should be careful to limit WHERE you use it as it could mess up MFC. So you should limit the use to where you need to access that library.

#ifdef DrawText
#undef DrawText
#endif
8
  • This results in error C2039: 'DrawText' : is not a member of 'PoDoFo::PdfPainter'. Than I thought maybe I should just undefine it and define it again to self as #define DrawText DrawText but I get same error with that too.
    – zar
    Nov 21, 2013 at 20:14
  • This is going to be rather annoying, you need to undef it JUST for the call to the other library, and then redefine it correctly
    – Mgetz
    Nov 21, 2013 at 20:15
  • 3
    You'll have to undefine it after the MFC headers are included, but before the PoFoDo library headers are included. Otherwise when the library headers are processed the compiler will incorrectly see that class PoDoFo::PdfPainter has a DrawTextW() member function instead of a DrawText() member function. Nov 21, 2013 at 20:33
  • To whomever downvoted... please post a reason, this is a perfectly valid answer to the question.
    – Mgetz
    Nov 22, 2013 at 1:24
  • -1 You are contradicting yourself. Even though you state that the scope of the "preprocessor hack" should be limited, you provide nothing to actually do so. You further correct your proposed solution in the comments, stating that you have to "redefine it [the macro] correctly", but again, provide nothing to actually implement this. Overall, this is a bad approach, appying a global solution to a local problem. Nov 22, 2013 at 10:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.