CMake links to static instead of shared target
This fails on Windows but is OK on Linux:
add_library(Foo SHARED foo.cpp)
add_executable(Bar main.cpp)
target_link_libraries(Bar PUBLIC Foo)
Build output:
>------ Build All started: Project: Test, Configuration: x64-Debug ------
[1/4] Building CXX object CMakeFiles\Bar.dir\main.cpp.obj
[2/4] Building CXX object CMakeFiles\Foo.dir\foo.cpp.obj
[3/4] Linking CXX shared library Foo.dll
[4/4] Linking CXX executable Bar.exe
FAILED: Bar.exe
cmd.exe /C "cd . && "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -E vs_link_exe --intdir=CMakeFiles\Bar.dir --rc=C:\PROGRA~2\WI3CF2~1\10\bin\100190~1.0\x64\rc.exe --mt=C:\PROGRA~2\WI3CF2~1\10\bin\100190~1.0\x64\mt.exe --manifests -- C:\PROGRA~2\MICROS~2\2019\COMMUN~1\VC\Tools\MSVC\1429~1.301\bin\Hostx64\x64\link.exe /nologo CMakeFiles\Bar.dir\main.cpp.obj /out:Bar.exe /implib:Bar.lib /pdb:Bar.pdb /version:0.0 /machine:x64 /debug /INCREMENTAL /subsystem:console Foo.lib kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib && cd ."
LINK Pass 1: command "C:\PROGRA~2\MICROS~2\2019\COMMUN~1\VC\Tools\MSVC\1429~1.301\bin\Hostx64\x64\link.exe /nologo CMakeFiles\Bar.dir\main.cpp.obj /out:Bar.exe /implib:Bar.lib /pdb:Bar.pdb /version:0.0 /machine:x64 /debug /INCREMENTAL /subsystem:console Foo.lib kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib /MANIFEST /MANIFESTFILE:CMakeFiles\Bar.dir/intermediate.manifest CMakeFiles\Bar.dir/manifest.res" failed (exit code 1104) with the following output:
C:\Users\Shahriar\Desktop\Test\out\build\x64-Debug\LINK : fatal error LNK1104: cannot open file 'Foo.lib'
ninja: build stopped: subcommand failed.
Build All failed.
I'm using Visual Studio with MSVC version:
Microsoft (R) C/C++ Optimizing Compiler Version 19.29.30136 for x86
Copyright (C) Microsoft Corporation. All rights reserved.
And CMake version:
cmake version 3.20.21032501-MSVC_2
Apparently it tries to link Bar to Foo (which is shared) statically.