問題描述
對于一個項目,我需要創建一個可執行文件,其中包含我使用的所有庫(opencv、cgal),以便在沒有這些庫的計算機上執行它.目前,這是我的 CMakeLists.txt(我使用 linux).
for a project I need to create an executable that includes all the libraries that I used (opencv, cgal) in order to execute it on a computer that has not those libraries. Currently, this is my CMakeLists.txt (I use linux).
cmake_minimum_required(VERSION 2.8)
#set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -Wall -O2")
project( labeling )
set(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
add_library(OpenCV STATIC IMPORTED)
add_library(CGAL STATIC IMPORTED COMPONENTS Core)
add_library(GMP STATIC IMPORTED)
find_package(OpenCV REQUIRED)
find_package(CGAL QUIET COMPONENTS Core )
find_library(GMP_LIBRARY gmp /usr/lib)
include(src)
include( ${CGAL_USE_FILE} )
include( CGAL_CreateSingleSourceCGALProgram )
set(EXECUTABLE_OUTPUT_PATH ../bin)
set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++")
include_directories( src )
include_directories( ${OpenCV_INCLUDE_DIRS} )
file(GLOB_RECURSE nei_SRC "src/*.cpp")
add_executable( nei_segmentation ${nei_SRC})
target_link_libraries( nei_segmentation ${OpenCV_LIBS} ${GMP_LIBRARY})
通過這種方式,我的可執行文件中只包含 GMP 和其他一些 C++ 庫.我的問題是:如何創建一個 makefile 以便以靜態方式自動包含所有庫并僅創建一個包含所有庫的大"可執行文件?你能幫我嗎?
In such a way only GMP and some other c++ libraries are included in my executable. My question is: How can I create a makefile in order to automatically including all the libraries in a static manner and creating only a "big" executable that contains all the libraries? Can you help me?
推薦答案
作為全局 CMake 設置,在 add_executable 之前添加這些行,對 gcc/clang 有效:
As global CMake settings, add these lines before add_executable, valid for gcc/clang:
set(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
set(BUILD_SHARED_LIBS OFF)
set(CMAKE_EXE_LINKER_FLAGS "-static")
關于現代 CMake (3.x+ - target_link_libraries doc),您可以將標志應用于特定目標,方式如下:
On Modern CMake (3.x+ - target_link_libraries doc), you can apply the flag to specific targets, in this way:
target_link_libraries(your_target_name -static)
如果您使用 MSVC,則必須設置編譯器和鏈接器標志:
If you're using MSVC, you have to set the compiler and linker flags:
set(CMAKE_FIND_LIBRARY_SUFFIXES ".lib")
target_compile_options(your_target_name [PUBLIC|PRIVATE] /MT)
target_link_options(your_target_name [PUBLIC|PRIVATE] /INCREMENTAL:NO /NODEFAULTLIB:MSVCRT)
如果您使用的是 MFC,則需要將標志指定為 1
見這里:
and if you are using MFC, you need to specify the flag to 1
see here:
set(CMAKE_MFC_FLAG 1)
這篇關于使用 CMake 編譯靜態可執行文件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!