The BUILDING_DLL definition is a custom preprocessor macro used in C++ projects, especially when building dynamic link libraries (DLLs) on Windows. It serves to differentiate between the build process of the DLL itself and the use of the DLL in another application. This distinction is important for correctly exporting and importing functions, classes, or symbols from the DLL.
In the context of a DLL, you often have two scenarios:
-
Building the DLL: When compiling the DLL, you need to export symbols (functions, classes, etc.) from the DLL so that they can be used by other applications or libraries. In Windows, this is typically done using the __declspec(dllexport) attribute.
-
Using the DLL: When another application or library is using (linking to) the DLL, it needs to import the symbols from the DLL. This is typically done using the __declspec(dllimport) attribute.
The BUILDING_DLL macro is used to control whether __declspec(dllexport) or __declspec(dllimport) should be applied. Here’s a typical usage pattern in a header file:
#define DLL_PUBLIC __declspec(dllexport)
#define DLL_PUBLIC __declspec(dllimport)
// Example function declaration
extern "C" DLL_PUBLIC void someFunction();
When the DLL itself is being compiled, BUILDING_DLL should be defined, usually through the build system or compiler flags. This will cause DLL_PUBLIC to be defined as __declspec(dllexport), indicating that someFunction should be exported.
When another application is including this header and using the DLL, BUILDING_DLL should not be defined. This will cause DLL_PUBLIC to be defined as __declspec(dllimport), indicating that someFunction is being imported from the DLL.
In the provided CMake example, the BUILDING_DLL macro is set for the target when compiling on Windows:
target_compile_definitions(ExcelLibrary PRIVATE BUILDING_DLL=1)
This ensures that when the DLL project is built, the BUILDING_DLL macro is defined, and __declspec(dllexport) is used. When the header file is used in another project that links to the DLL, BUILDING_DLL should not be defined, and __declspec(dllimport) will be used instead.