1、使用Release模式
set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -s") set(CMAKE_BUILD_TYPE "RELEASE")
2、使用strip命令删除调试信息等
set(CMAKE_STRIP "strip") add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD COMMAND ${CMAKE_STRIP} "$<TARGET_FILE:${PROJECT_NAME}>" COMMENT "Strip debug symbols done on final binary.")
例如一个HelloWorld程序的原CMakeLists.txt没优化前如下
cmake_minimum_required(VERSION 3.20) project(HelloWorld) set(CMAKE_CXX_STANDARD 17) add_executable(HelloWorld HelloWorld.cpp)
优化前文件体积3183KB
优化后
cmake_minimum_required(VERSION 3.20) project(HelloWorld) set(CMAKE_STRIP "strip") set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -s") set(CMAKE_BUILD_TYPE "RELEASE") set(CMAKE_CXX_STANDARD 17) add_executable(HelloWorld HelloWorld.cpp) add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD COMMAND ${CMAKE_STRIP} "$<TARGET_FILE:${PROJECT_NAME}>" COMMENT "Strip debug symbols done on final binary.")
优化后体积912KB,当然如果你如果需要保留exe文件调试信息,请酌情使用RELEASE
标签:可执行文件,输出,set,CMAKE,HelloWorld,add,STRIP,RELEASE,Cmake From: https://www.cnblogs.com/passedbylove/p/17712860.html