Compile check if compiling as static library

c++, compilation, static-libraries, visual-studio-2010

Solution

There is no such thing in predefined macro list - http://msdn.microsoft.com/en-us/library/b0084kay%28v=vs.100%29.aspx .

But by default MSVC adds `_LIB` to preprocessor definition list, if it's a "static library" project. (also it adds `_USRDLL` for DLLs)

Edit: In Visual Studio 2017 the definition for DLLs is `_WINDLL` (from the "Windows Dynamic Link Library" property sheet applied by the IDE). The `_LIB` definition is no longer available.

An alternative solution is to add a property sheet to the project (checked into your version control repository) with the following preprocessor definition: `_$(OutputType);%(PreprocessorDefinitions)`.

`$(OutputType)` will resolve as "library" for DLLs and "staticlibrary" for static libraries, resulting in `_library` and `_staticlibrary` definitions respectively (or `_exe` for applications).

`%(PreprocessorDefinitions)` will stack definitions from previous property sheets. Make sure it is included in the project properties as well!

To add a property sheet, navigate to View | Other Windows | Property Manager in Visual Studio.

Problem

How can i check at compilation if the project is being compiles as a lib ? (static library) Is there some kind of static assert or some other flag i can check? I can't add a preprocessor variable myself, because it's a utility that will be used in other projects across the company. So I'm wondering if there's some preprocessor flag that is is being sent by default or something. I'm using Visual Studio 2010

Original source