10

When building my project with CMake, I would like it to link to libraries statically (if available). Right now, it finds .dll.a files, regardless of the existence of .a files.

For example, take linking to libpng in a small sample project:

cmake_minimum_required(VERSION 3.15)
project(Test)

add_executable(Test main.cpp)

find_package(PNG REQUIRED)
message(${PNG_LIBRARIES})
target_link_libraries(Test PRIVATE ${PNG_LIBRARIES})

For the message, it outputs

C:/msys64/mingw64/lib/libpng.dll.aC:/msys64/mingw64/lib/libz.dll.a

But the libpng.a and libz.a files are also available in the same directory. How can I tell CMake to link with .a files?

I am using MinGW-w64 with msys64 on Windows 10, but would prefer a solution that is cross-platform.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
Rheel
  • 410
  • 4
  • 19
  • 3
    It's quite incredible, and quite telling that nobody has answered this seemingly simple question. Especially considering how trivial it is to link against a static library if you have control over the linker call, or just the compiler frontend call. – gonzo Jul 16 '22 at 19:19
  • Does this answer your question? [How do I tell CMake to link in a static library in the source directory?](https://stackoverflow.com/questions/14077611/how-do-i-tell-cmake-to-link-in-a-static-library-in-the-source-directory) – Tom Jul 08 '23 at 06:01
  • @Tom unfortunately not. That only works if you're specifically linking with a static library of which you know the exact location beforehand. My question is the more general case, where CMake is the one looking up that location. For example: when this is part of an open-source project, the library archive might be in any location. – Rheel Jul 15 '23 at 18:33
  • @Tsyvarev - any thoughts? – einpoklum Aug 23 '23 at 12:40
  • @AlexReinking - perhaps you might have an idea about this? – einpoklum Aug 23 '23 at 12:41
  • It seems to me that the problem is in FindPNG: Looking at my cmake 3.26.3 installed modules: FindPNG.cmake searches with a find_library for any library with a NAME like png${v} libpng${v} libpng${v}_static. Apparently, it finds the dynamic one first and stops looking for the static one. – André Aug 31 '23 at 12:32

0 Answers0