agnul
agnul

Reputation: 13058

How do I tell cmake I want my project to link libraries statically?

I'm trying to build an OpenCV-based project using CMake, running on Linux. So far my CMakeLists.txt files looks something like

FIND_PACKAGE (OpenCV REQUIRED)
...
TARGET_LINK_LIBRARIES (my-executable ${OpenCV_LIBS})

but this results in dynamically linked libraries. How do I link with static libraries?

Upvotes: 28

Views: 48934

Answers (7)

RobertJMaynard
RobertJMaynard

Reputation: 2257

on the add_library line specify static. See https://cmake.org/cmake/help/latest/command/add_library.html

Correction since you are looking to link against a static library I would look into the CMAKE_FIND_LIBRARY_SUFFIXES property

Upvotes: 3

Li Gewei
Li Gewei

Reputation: 11

SET (CMAKE_EXE_LINKER_FLAGS "-static")

Upvotes: 0

agnul
agnul

Reputation: 13058

You build static OpenCV libraries by just setting the BUILD_SHARED_LIBS flag to false in CMake. Then all you need to do to build your own application with those static libraries is to add a dependency on OpenCV in your CMakeLists.txt:

FIND_PACKAGE (OpenCV REQUIRED)
...
TARGET_LINK_LIBRARIES (your-application ${OpenCV_LIBS})

and CMake will take care of everything.

Upvotes: 13

bcook
bcook

Reputation: 147

Actually this issue seems to have already been fixed in the OpenCVConfig.cmake that comes with OpenCV. All you have to do is define OpenCV_STATIC in your CMakeLists.txt. I.e.

set(OpenCV_STATIC ON)
find_package(OpenCV REQUIRED)

Upvotes: 13

pszilard
pszilard

Reputation: 1962

Note that gcc refuses to link if you pass the -static option, but you have dynamic libs in the link arguments - which you will if you just simply use FindOpenCV.cmake and this picks up the dynamic libs (I don't know how OpenCVConfig.cmake behaves though)...

Upvotes: 1

pszilard
pszilard

Reputation: 1962

AFAIK that's a bit tricky, because CMake, more precisely the find_library command, prefers shared libs and finds those if both shared and static are available.

I'm still looking for a good solution myself to be able to compile binaries "as static as possible", but I've found no elegant solution yet. The only way it would surely work is to implement everything through custom FindXXXX modules.

Upvotes: 5

jkerian
jkerian

Reputation: 17046

To link everything statically, I believe you're looking for CMAKE_EXE_LINKER_FLAGS (add -static).

Are you using the 'simple method' of OpenCVConfig.cmake? or the older FindOpenCV.cmake?

Upvotes: 7

Related Questions