Compiling a static executable with CMake

后端 未结 2 1294
耶瑟儿~
耶瑟儿~ 2020-11-28 08:16

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

相关标签:
2条回答
  • 2020-11-28 08:36

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

    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)
    

    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)
    

    and if you are using MFC, you need to specify the flag to 1 see here:

     set(CMAKE_MFC_FLAG 1) 
    
    0 讨论(0)
  • 2020-11-28 08:41

    Add these lines after add_executable(MyExec "main.c") (for exemple) :

    target_link_libraries(MyExec PUBLIC "-static")

    or before : link_libraries("-static")

    0 讨论(0)
提交回复
热议问题