Tutorial -> static / dynamic Libraries on Windows

Hey guys,

I’m trying to understand several things regarding the building of static/shared libraries on Windows.
As the tutorial states in step 10: the BUILD_SHARED_LIBS options offers an switch for either building a static or dynamic library. For Windows you need to set up dllimport/dllexport aswell…
So building a dll succeeds, but when I set BUILD_SHARED_LIBS to off (directly after the option is defined:

option(BUILD_SHARED_LIBS “Build using shared libraries” ON)

I get a linker Error:

tutorial.obj : error LNK2019:: unresolved external Symbol … __declspec(dllimport) double __cdecl mathfunctions::sqrt(double) …

As I understand it, this should work out of the box, so can you please tell me if my assumption is wrong or confirm the issue?

Things get even more weird, when trying to build a static version anyways:

  • Opt1. naivly remove the DECLSPEC-stuff in MathFunctions.h → Ok, but needs manual adjustment to switch static/dynamic, so …
  • Opt2. define another variable on CMake-side to check for windows system and requesting shared library (

# building on windows
target_compile_definitions(MathFunctions PRIVATE “WIN_DLL”)
target_compile_definitions(MathFunctions PRIVATE “EXPORTING_MYMATH”)

) and check that variable in the header instead of _WIN32 (

#if defined(WIN_DLL)
# if defined(EXPORTING_MYMATH)

) → Ok, so in result it’s the same effect as Opt1 and obviously not surprising, but…

  • Opt3. is born as a failure: I forgot to check for ${BUILD_SHARED_LIBS} so just (

# building on windows
target_compile_definitions(MathFunctions PRIVATE “WIN_DLL”)

) → WTF, why is this working??? As I understand it _WIN32 and CMAKE_HOST_WIN32 should be defined/true, aslong as you are on windows… so basicly and semanticly it should be all the same, but why does the _WIN32-attempt throws an linker error? Is there an failure in the tutorial-code or am I maybe misunderstanding what happens/should happen.

Can you please test and confirm/resolve this behaviour?

Confused regards

Tut. step 10 → Step 10: Selecting Static or Shared Libraries — CMake 3.27.6 Documentation
code ref → CMake/Help/guide/tutorial/Complete at master · Kitware/CMake (github.com)

edit: edit format due to readability (sorry first post for me :wink:

FYI, this makes the cache option useless; CMake will default to STATIC libraries for any declared after this.

Cc: @betsy.mcphail for the tutorial bits