views:

135

answers:

4

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?

Update: The default build for OpenCV builds only dynamic libraries, and of course trying to link those statically will fail. If I build static OpenCV libraries the only option seems to be manually adding the full paths to the libraries in the TARGET_LINK_LIBRARIES command

Solved, sort of: Building a static OpenCV and listing all the libraries in the TARGET_LINK_LIBRARIES command works, but it looks like I have to explicitly specify dependencies on things like librt and libpthread. I suspect the OpenCV_LIBS macro took care of those as well.

... and another thing: the OpenCV_LIBS macro works fine even with static libraries, so all I needed to do was just pointing CMake at a static OpenCV build.

+1  A: 

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?

jkerian
A: 

on the add_library line specify static. See http://www.cmake.org/cmake/help/cmake-2-8-docs.html#command:add_library

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

RobertJMaynard
I think the add_library command is to generate an output binary. In this case, specifying STATIC causes it to generate .a.
jkerian
The static keyword for add_library specifies what type of library it generates, it is not for when generating the binary.
RobertJMaynard
Perhaps I misunderstood, but I thought the OP was trying to link with a static library, not generate one.
jkerian
yep, I'm not creating a library, I want to link (statically) to the OpenCV libraries.
agnul
+1  A: 

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.

pszilard
+1  A: 

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)...

pszilard