user14416
user14416

Reputation: 3032

How to specify the linking type in CMake?

In my CMake script I need to specify for different library, that my project is linked against, different types of linking for gcc. It is well-known to use -Wl,-Bstatic and -Wl,-Bdynamic options for such kind of mixing. But is it possible to specify this somehow in cmake script?

Upvotes: 4

Views: 837

Answers (2)

Adam Bowen
Adam Bowen

Reputation: 11240

We use a couple of macros that adjust CMake's preferred search order on Linux/MacOSX to switch between dynamically and statically linked libraries

macro( prefer_static )
    if( NOT WIN32 )
        list( REMOVE_ITEM CMAKE_FIND_LIBRARY_SUFFIXES   ".a" )
        list( INSERT      CMAKE_FIND_LIBRARY_SUFFIXES 0 ".a" )
    endif()
endmacro()

macro( prefer_dynamic )
    if( NOT WIN32 )
        list( REMOVE_ITEM CMAKE_FIND_LIBRARY_SUFFIXES ".a" )
        list( APPEND      CMAKE_FIND_LIBRARY_SUFFIXES ".a" )
    endif()
endmacro()

we then call the appropriate prefer_static() or prefer_dynamic() routine prior to calling find_library(...) or find_package(...). This has the advantage of "falling back" on a shared library when a static library is not available, or vice-versa.

This won't work for Windows builds because you always link to a .lib file with Visual Studio and (AFAIK) there's no a straightforward way to determine if it's a static or dynamic library.

Upvotes: 2

bikram990
bikram990

Reputation: 1115

In CMake find_library can be used for this purpose.

find_library(VAR libMyLib.a) OR SET(CMAKE_FIND_LIBRARY_SUFFIXES ".a") find_library(VAR MyLib)

Upvotes: 0

Related Questions