Is preprocessor blindly replace the defines? - c++

I have a class that has a member function called SendMessage. No member function named SendMessageA exists in the project.
Project is multibite, so I have a define
#define SendMessage SendMessageA
If I call SendMessage somewhere in that class, will my project call SendMessage or SendMessageA ?
If the replace is made by preprocessor,the project should not compile. Right ?
But I see in a dump that SendMessageA is called ... end eip register is not in any VAD
EDIT
A more specific question: is preprocessor blindly replace the defines ? or first checks for a match in the class ?

The Preprocessor runs through your code before compilation.
So any SendMessage would be converted into a SendMessageA. The compiler will then look for a function called SendMessageA and call it.

How C++ preprocessor works
In case of #define A B preprocessor replaces ALL occurences of A with B. It is pure substitution.
Will my project call SendMessage or SendMessageA ?
Your project will call either SendMessageA or SendMessageW - depending on whether it was compiled with unicode support or not. There's no SendMessage function - it doesn't exist.
f the replace is made the project should not compile.
SendMessageA is declared within <widnows.h> (or in a header that is included from windows.h) - somewhere, and its linking info is within one of base system libraries (User32.lib, I think). If you're on windows, there's a very good chance <windows.h> is #included from somewhere, and corresponding *.lib is already in linker dependencies.
--EDIT--
A more specific question: is preprocessor blindly replace the defines ?
Yes, preprocessor blindly replaces defines. For non-blind replacement you have templates, but they have their own limitations. Some thing that can be done with preprocessor cannot be done with templates and vice versa. Preprocessor have stringize operator, templates have type-checking and metaprogramming.
My problem is why sometimes the member function SendMessage is called because the code works (most of the time)
If you have SendMessage method in your code (BAD idea on windows platform - clashes with system macro, replace with sendMessage() or use different name, because even namespaces won't help you to avoid omnipresent preprocessor) your method (not SendMessageA/SendMessageW) will be called from *.cpp ONLY if <windows.h> was not included in that *.cpp.
Compiler operates at one file at a time, and has no knowledge of thing that go on in other files, so if there's no <windows.h> #included, your method will be called, because preprocessor won't have any knowledge about SendMessage #define (from <windows.h>). If <windows.h> is included, then ALL occurences of SendMessage will be replaced with SendMessageA/SendMessageW, because preprocessor does its job first.
One possible solution in your situation would be to avoid using naming convention similar to the one in Win API. I.e. make sure that function names don't start with capital letter. That'll solve many problems, but you'll still get minor trouble from min/max macros.

The preprocessor works as a text macro processor. If a macro is defined, all occurrences of the macro are replaced with it's definition.
#define blabla some_real_stuff
struct blabla /* blabla will be replaced with some_real_stuff */
{
void method();
};
int main()
{
some_real_stuff x;
x.method();
}

In the Windows API, there are the two functions SendMessageA and SendMessageW. You will be calling one of these two, depending on what #defines you have in your program.
Are you sure that is not what happens?
Edit: oh wait. Is your #define SendMessage SendMessageA before the definition of the SendMessage member function in your source? If so, the compiler will simply use SendMessageA for the name of the member. Otherwise, your function will be SendMessage, but the rest of your program will call the built in Windows function SendMessageA.
If you have many source files, maybe some of them will know about the #define, while others won't.
My recommendation is to rename the member function to something else and dispense with the #define.

Related

How to deal with WinAPI macros overriding some function names?

<windows.h> defines macroses for Ansi and Unicode versions of WinAPI.
I have a function named SendMessage in my class library. It works fine until <windows.h> is included before including my library. In this case SendMessage is overrided by the macros and the function name becomes SendMessageA or SendMessageW.
Is it possible to somehow deal with it without changing the name of the function in order to save compatibility with older versions of the library?
The real problem is that WinAPI's function definitions are at the C-preprocessor level, and so you have to write some ugly code to try to coexist with them.
If at all possible, you should rename your codebase's functions so that there is no collision with WinAPI.
Otherwise, you can write code like #undef SendMessage to undefine WinAPI's definition of this function before defining your own function.
If you need to switch between defining your own functions and using WinAPI's function macros, you can also use the #pragma push_macro and #pragma pop_macro functionality to preserve the macro before the undef and restore it afterwards.

Fix Compiler Errors after Removing #include windows.h and Relative Functions Calls

I'm working on VS2017 on Windows 10. I have a a working FSM with Messaging console application, which however has a couple of Windows libraries (windows.h and winmm.lib) and a non-standard C++ library (conio.h). I want to remove and/or replace these libraries in order to be able to port the C++ code to OSX. I will remove and/or replace/adapt any current functionality as necessary.
However, after proceeding I get many compiler errors that I cannot explain. I searched for many hours but cannot find any useful references and I need some help figuring these out.
After I remove #include windows.h from a particular utility header file (ConsoleUtils.h) and remove one of its functions that uses windows.h, as well as all calls to this function, I get the following compiler errors:
In MessageDispatcher.cpp:
class MessageDispatcher has no member DispatchMessageW
Well, MessageDispatcher has a function DispatchMessage() (no 'W' at the end). I'm really puzzled by this. If I hover the mouse pointer over the red curly line in the definition of MessageDispatcher::DispatchMessage, a popup displays
"#define DispatchMessage DispatchMessageW expands to DispatchMessageW"
However, I don't have any such #define any where in my code! I even did a text search for "DispatchMessageW" in the entire solution and there are no instances of this text.
In MessageDispatcher.cpp:
Additionally, inside the DispatchMessage() function two private members are inaccessible (Discharge() and PriorityQ), both of which are properly declared and defined, and have no reference to windows.h.
In two other classes that call MessageDispatcher::DispatchMessage() I get the same error as described in '1' above.
If I add #include windows.h back, all the errors go away, and the project builds and runs with no problem.
What could be causing these errors, and what could I do to fix them?
Somewhere after you define the MessageDispatcher class, and before you use it, something includes <windows.h> or some other windows header that is causing the DispatchMessage macro to be defined.

How do I resolve naming conflicts with headers that use the preprocessor to redefine common function names?

EDIT: I found a similar question, and the answers are basically that windows.h is bad and you must either rename your functions or #undef the macros: Other's library #define naming conflict
However, I believe mine is still different due to the conflicting behavior of LoadLibrary under debug and release builds.
I am programming on Windows using Visual Studio and I ran into a few peculiar issues with preprocessor directives used by windows.h and the headers it includes.
Our project had a function in its own namespace, MyProject::FileManager::CreateFile(). After including windows.h our code failed to compile due to a linker error stating that it could not resolve MyProject::FileManager::CreateFileW (note the W at the end of the function name). This was not a static function, it was a member function of a FileManager object that was being called with file_manager.CreateFile(...).
When highlighting the function in Visual Studio a tooltip displayed the following:
#define CreateFile CreateFileW
We were puzzled but just renamed the function as a workaround. However later we ran into a similar issue with the LoadLibrary function we were trying to use from the Windows API. Compiling in Debug mode, LoadLibrary was defined as LoadLibraryW() which took an LPCWSTR (wide string) as a parameter. When I tried building in Release mode this function was now defined as LoadLibraryA() which takes a normal LPCSTR. This broke our build because the code was written under the assumption that LoadLibrary took an LPCWSTR.
So, my question is, how should a programmer deal with this? Should I just wrap my calls to LoadLibrary with #ifdef's checking for Debug or Release mode? Or is there a more simple solution?
Also, I found an interesting header file on github which appears to have been created for the sole purpose of #undef'ing all these function names:
https://github.com/waTeim/poco/blob/master/include/Poco/UnWindows.h
There are few things I generally do to cope with this:
Isolate all Windows system calls in a Windows-specific layer. For example, if I'm working with the file system API, I'll typically have win/filesystem.h and win/filesystem.cpp to wrap all the calls. (This is also a good place to convert Win32 errors into std::system_error exceptions, remove unneeded/obsolete/reserved parameters, and generally make the Windows API more C++ friendly.)
Avoid using Windows-specific types. Allowing definitions like DWORD, LPTSTR and BOOL to infiltrate all levels of your code makes dealing with Windows.h that much more difficult. (And porting too.) The only files that should #include <Windows.h> should be your wrapper C++ files.
Avoid using the Windows redirection macros yourself. For example, your wrapper layer should call CreateFileW or CreateFileA directly instead of relying on the macro. That way, you don't need to depend on the Unicode/Multi-byte project setting.
Example
win/filsystem.h might contain definitions like this:
namespace win32
{
class FileHandle
{
void* raw_handle_;
public:
// The usual set of constructors, destructors, and accessors (usually move-only)
};
FileHandle CreateNewFile(std::wstring const& file_name);
FileHandle OpenExistingFile(std::wstring const& file_name);
// and so on...
}
Any part of your code can include this file to access the file system API. Since win/filesystem.h does not itself include <Windows.h>, the client code will be uncontaminated by the various Win32 macros.
The problem here is that windows.h tries to support two different string models: strings consisting of single-byte characters and strings encoded in unicode (defined by microsoft as two-byte characters). Almost all of the Windows API functions have two different versions, one that takes single-byte character strings and one that takes two-byte character strings. You're supposed to write your code with the generic names (such as CreateFile, LoadLibrary, etc.) and let windows.h take care of mapping those names to the actual API functions. For single-byte characters those two are CreateFileA and LoadLibraryA; for two-byte characters they are CreateFileW and LoadLibraryW. And there are a bajillion more, of course. You choose the model at compile time by defining the macro UNICODE in every compilation unit.
Incidentally, the 'A' suffix stands for "ANSI", and the 'W' suffix stands for "wide character".
This is particularly insidious when you write code that tries to isolate the Windows dependencies into a handful of source files. If you write a class that has a member function named CreateFile, it will be seen in source files that don't use windows.h as CreateFile, and in source files that do use windows.h as CreateFileA or CreateFileW. Result: linker errors.
There are a several ways around this problem:
always #include <windows.h> in every header file; that's a compiler performance killer, but it will work. (windows.h was a major motivator for precompiled headers in early C++ compilers targeting windows)
always use the doctored name, either CreateFileA or CreateFileW; that will work, but at the cost of losing the flexibility of being able to change the underlying string model when you're making API calls; whether that matters is up to you.
don't use any of the Windows API names; potentially painful if you use the same naming convention as Windows; not at all painful if you use snake case, i.e., all lower-case with underbars to separate words. For example, create_file. Alternatively, use a local prefix or suffix: MyCreateFile or CreateFileMine.

How to suppress #define locally?

Just caught a silly bug. I have a zip processing library with a CreateFile() function in it. Winbase.h, included somewhere deep in my headers, redefines it as CreateFileW and linker goes nuts.
Of course I will exclude winbase in this particular case. It just shouldn't be in the scope in the first place. But the theoretical question is still interesting,
Is there a way to suppress some defines locally?
You can get around the macro by putting parentheses around the name:
(CreateFile)(arguments);
This works because the macro CreateFile is a function-like macro (i.e. it takes a list of arguments in parentheses); the right parenthesis after the name doesn't match the syntax for using a function-like macro, so the preprocessor does not expand it.
Of course, the "right" solution is to name the function properly, i.e., create_file. <g>
Removing the offending header file is ALWAYS the best solution for this (especially one as large as windows.h or winbase.h - they are included far too freely for my taste in many projects).
The only other solution is #undef offending_symbol.
Of course, another important thing is "do not use names that match the Windows/Linux system call names" - but CreateFile is a very obvious name for a function that creates a file, so I can see the temptation.
Preprocessor macros have no notion of C++ scope. #defines are just text replacements. If you want to have a 'local' #define, you do something like this:
#define CreateFileW CreateFile
... // here I can use the macro
#undef CreateFileW
Or in your case
#undef CreateFileW
... // Here the macro is not available
#define CreateFileW CreateFile
There is
#undef
which removes defines (but nothing else).
Apart from the aforementioned #undef there technically is not much you can do against #defines, at least not portably.
The best way is to not use #define at all, or at least as little as possible and as constrained as possible. Sometimes you just need a macro to generate some boilerplate code a few times. Be sure to #undef that macro once you are done. The only other valid applications of #define I can think of are include guards and flags for conditional preprocessing.
For #define-deseases like the WinAPI headers you just should constrain them as much as possible. Don't use the #defined types of that API in your headers. You almost never want to use an API all over your application, so use it only in the cpps of a small layer around the API. Reducing the dependencies that way gives a lot more than just disinfecting the rest of your code.

Using the function of a specific library

I have a problem: I would like to use the function abs of the library complex.
However, I undergo an error warning me the function abs used is #define abs(x) (x > 0) ? x : -(x).
Thus, I think the problem comes from my imports. Because of I also include the stdio and stdlib libraries, the compiler may use the function abs defined in one of these libraries.
So my question is: how can I use the function abs of the library complex without removing any import ?
Thanks a lot in advance for your response.
Wrap parens around it.
(abs)(whatever);
This will force the compiler to use the function version because the macro no longer matches.
Function-like macros work by matching an identifier followed by a left paren (. Since we've wrapped the function name itself in parens, we have instead an identifier followed by a right paren ), which fails to match the macro. The parens are semantically transparent, but they inhibit the macro syntax.
IIRC, it was splint the C checker which taught this to me. While writing a postscript interpreter, I created nice short macros to access the stack.
#define push(o) (*tos++ = (o))
#define pop() (*--tos)
Which were great until the tricky parts where they were part of an expression involving tos. To avoid undefined behavior, I had to create function versions and use those for those tricky spots. For the new design, I skipped the macros altogether.
Edit: I've got a nagging feeling that it was actually the Coelocanthe book (Peter Van Der Linden's Deep C Secrets) where I learned this, the above situation being where I first needed it. IIRC his example involved putchar or getchar which are often implemented as both functions and macros in conforming C implementations.
Use #undef
#include "header1.h"
#include "header2.h"
#undef abs // remove abs macro
x = std::abs(y);
Whilst several suggestions above are very good, I would take a completely different angle. It is almost certainly something like windows.h that causes the "bad" macro definition of abs(). You should be able to NOT include "windows.h" in the file that does the complex math [in most types of programs, at least] (I'm not aware of a single function in Windows that takes complex<T> as an argument, so I'm pretty certain you don't need both "complex.h" and "windows.h" in the same source file. This method is called "isolating the system dependencies", and doing that is a very good thing.
Have a look at your code, and find where you are ACTUALLY using windows functions, and then only include "windows.h" in the files that actually need it. You'll probably find, if you are using Visual Studio, that "windows.h" is included as part of "stdafx.h", which means that all sort of interesting macros etc are being included all over the place, because "stdafx.h" is included in ALL source files.
Both #undef and parentheses solutions will work but I would advise to have something a little stronger, because both those solutions will required you to do them every time you want to call abs and next time you may forget and result in a bug.
what you can do:
change the name of your function to less common name : absolute, myAbs etc...
put you function\class under a name space (for C++ not for C) then the calls are explicit myNameSpace::abs(x)
If it won't work as the comment here suggested I would still warp the call in my function:
type myAbs(type param)
{
return (abs)(param);
}