我如何告诉 cmake 我希望我的项目静态链接库?
我正在尝试使用 CMake 构建一个在 Linux 上运行的基于 OpenCV 的项目。到目前为止,我的 CMakeLists.txt
文件看起来很像
FIND_PACKAGE (OpenCV REQUIRED)
...
TARGET_LINK_LIBRARIES (my-executable ${OpenCV_LIBS})
,但这会产生动态链接库。如何链接静态库?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
实际上这个问题似乎已经在OpenCV自带的
OpenCVConfig.cmake
中得到了修复。您所要做的就是在CMakeLists.txt
中定义OpenCV_STATIC
。 IEActually this issue seems to have already been fixed in the
OpenCVConfig.cmake
that comes with OpenCV. All you have to do is defineOpenCV_STATIC
in yourCMakeLists.txt
. I.e.您只需在 CMake 中将
BUILD_SHARED_LIBS
标志设置为 false 即可构建静态 OpenCV 库。然后,使用这些静态库构建您自己的应用程序所需要做的就是在CMakeLists.txt
中添加对 OpenCV 的依赖项:CMake 将处理所有事情。
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 yourCMakeLists.txt
:and CMake will take care of everything.
要静态链接所有内容,我相信您正在寻找
CMAKE_EXE_LINKER_FLAGS
(添加-static
)。您使用 OpenCVConfig.cmake 的“简单方法”吗?或者旧的 FindOpenCV.cmake?
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?
AFAIK 这有点棘手,因为 CMake(更准确地说是 find_library 命令)更喜欢共享库,并在共享库和静态库都可用的情况下查找这些库。
我自己仍在寻找一个好的解决方案,以便能够“尽可能静态”地编译二进制文件,但我还没有找到优雅的解决方案。它肯定有效的唯一方法是通过自定义 FindXXXX 模块来实现所有内容。
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.
在 add_library 行指定 static。请参阅 https://cmake.org/cmake/help/latest/command/add_library .html
更正,因为您正在寻找链接到静态库,所以我会研究
CMAKE_FIND_LIBRARY_SUFFIXES 属性
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
请注意,如果您传递 -static 选项,但 gcc 拒绝链接,但链接参数中有动态库 - 如果您只是简单地使用 FindOpenCV.cmake 并且它会获取动态库(我不知道 OpenCVConfig.cmake 的行为如何)...
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)...