[zt]CMake代码优化编译选项

当在Mac上发现程序运行速度慢,可能是因为未开启编译优化。通过在CMakeLists.txt中设置CMAKE_C_FLAGS和CMAKE_CXX_FLAGS为-O2或-O3可以显著提升程序速度。确保在CMakeLists.txt文件顶部设置默认构建类型为Release,并分别设定不同构建类型的编译标志,例如使用-Wall-Wextra进行警告检查,-g用于调试,-O3用于发布版本的优化。若CMAKE_BUILD_TYPE已缓存,用户需手动切换到Release模式以应用优化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://www.ztyii.com/ex/cmake-o2-opt/

Mac有一次系统升级后,发现clang不支持了openmp了,最后brew安装了clang-omp。但是好不容易配置起来后发现程序运行速度巨慢,今天发现没有打开编译优化,在CMakeLists.txt文件中加入以下编译选项即可(o2优化,甚至o3):

SET(CMAKE_C_FLAGS “KaTeX parse error: Double subscript at position 9: {CMAKE_C_̲FLAGS} -O2") SE…{CMAKE_CXX_FLAGS} -O2”)

程序速度提升4~5倍

https://www.it1352.com/1984337.html

To address the first issue, you should be able to do this early in your CMakeList:

if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release)
endif()

set(CMAKE_CXX_FLAGS “-Wall -Wextra”)
set(CMAKE_CXX_FLAGS_DEBUG “-g”)
set(CMAKE_CXX_FLAGS_RELEASE “-O3”)

This will make sure that if you do not specify a build type at all, it will default to “Release” and thus CMAKE_CXX_FLAGS_RELEASE will be used.

The second one is harder to tackle. Variables passed from the command line (such as CMAKE_BUILD_TYPE=Debug) are cached by CMake and thus re-used in subsequent invocations (that is necessary, since CMake can re-trigger itself if you modify its inputs between builds).

The only solution is to make the user switch the build type explicitly again, using cmake … -DCMAKE_BUILD_TYPE=Release.

Consider why this is necessary: as I said, CMake can re-trigger itself as part of a build if CMake’s input (CMakeLists.txt files or their dependencies) has changed since last CMake ran. In such case, it will also be run without command-line arguments such as -DCMAKE_BUILD_TYPE=whatever, and will rely on the cache to supply the same value as last time. This scenario is indistinguishable from you manually running cmake … without additional arguments.

I could provide a hacky solution to always reset CMAKE_BUILD_TYPE to Release if not specified explicitly on the command line. However, it would also mean that a buildsystem generated as Debug would get re-generated as Release if automatic re-generation happened. I am pretty sure that’s not what you want.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值