Preprocessor macro without C ++ replacement

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

#define identifier replacement 

However, sometimes I come across a macro definition that does not contain a replacement. For example, in afxwin.h, the following preprocessor definition exists:

 #define afx_msg // intentional placeholder 

My questions:

  • What happens during compilation when a preprocessor definition is used that has no replacement? Is it just ignored? For example, the line afx_msg void OnAddButton(); will become void OnAddButton(); ?
  • What is the purpose of using a preprocessor without replacement? Does it just make the code more understandable?
+6
source share
3 answers

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

There are several reasons why you will use something like this. One of them is just to use the macro in #ifdef and similar constructors.

Another is conditional compilation. Typical use cases are public APIs and DLL exports. On Windows, you need to mark a function exported from a DLL (when creating a DLL) or imported from a DLL (when linking to a DLL). ELF systems do not require such declarations. Therefore, in the headers of the public library, you often see the following code:

 #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(); 

Another reason might be a code processing tool. Perhaps you have a tool that parses the source code by extracting a list of functions with a specific marker. You can define such a marker as an empty macro.

+10
source
 #define bla 

just defines bla .

you can use it with

 #ifdef bla ... place some code here ... #endif 

a typical use case is #define DEBUG to enable special pieces of code in debug mode.

Another way to install things from the "outside":

  g++ -DDEBUG x.cpp 

which also installs the macro DEBUG.

And each header file should have something like:

 #ifndef THIS_HEADER_INCLUDE_GUARD #define THIS_HEADER_INCLUDE_GUARD ... rest of header file ... #endif 

It just protects your header file for (recursively) more than once.

Some may be performed with specific implementation of #pragma once .

+3
source
  • the preprocessor processes it, deleting it and replacing nothing
  • there can be many reasons, including readability, portability, custom compiler functions, etc.
+1
source

All Articles