Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preprocessor macro without replacement C++

Tags:

c++

macros

According to cplusplus.com, the syntax to define a macro is:

#define identifier replacement

However, I sometimes stumble upon a macro definition which doesn't contain a replacement. For example in afxwin.h, there is the following preprocessor definition:

#define afx_msg         // intentional placeholder

My questions:

  1. What happens at compile-time when a preprocessor definition that doesn't have a replacement is used? Is it simply ignored? For example, does the line afx_msg void OnAddButton(); become void OnAddButton();?
  2. What is the purpose of using preprocessor without replacement? Is it simply to make code more clear?
like image 920
A.P. Avatar asked Sep 02 '15 12:09

A.P.


People also ask

What to use instead of #define in C?

If you accidentally redefine a name with a #define , the compiler silently changes the meaning of your program. With const or enum you get an error message.

What does ## mean in macro?

The double-number-sign or token-pasting operator (##), which is sometimes called the merging or combining operator, is used in both object-like and function-like macros. It permits separate tokens to be joined into a single token, and therefore, can't be the first or last token in the macro definition.

What is preprocessor macro?

Macros allow you to write commonly used PL/I code in a way that hides implementation details and the data that is manipulated and exposes only the operations. In contrast with a generalized subroutine, macros allow generation of only the code that is needed for each individual use.


1 Answers

"Nothing" (no text) is a valid replacement text for a macro. It will simply be removed (more precisely, replaced by nothing) by the preprocessor.

There are multiple reasons why you'd use something like this. One is to simply use the macro in #ifdef and similar constructrs.

Another is conditional compilation. A typical use case is public APIs and DLL exports. On Windows, you need to mark a function as exported from a DLL (when building the DLL) or as imported from a DLL (when linking against the DLL). On ELF systems, no such declarations are necessary. Therefore, you'll often see code like this in public library headers:

#ifdef _WIN32
  #ifdef BUILDING_MYLIB
     #define MYLIB_API __declspec(dllexport)
  #else
     #define MYLIB_API __declspec(dllimport)
  #endif
#else
  #define MYLIB_API
#endif

void MYLIB_API myApiFunction();

Yet another reason could be code processing tools. Perhaps you have a tool which parses source code, extracting a list of functions with a certain marker. You can define such a marker as an empty macro.

like image 185
Angew is no longer proud of SO Avatar answered Oct 15 '22 11:10

Angew is no longer proud of SO